Esempio n. 1
0
File: bot.py Progetto: Vityan/123
def hand_text(message):
    if message.text == "/weather":
        string_weather = weather.getweather('Севастополь')
        bot.send_message(message.chat.id, string_weather)
        botan.track(config.botan_key, message.chat.id, message, 'Погода ')
        return
    elif message.text[:9] == "/weather ":
        s = message.text.split()
        city = s[1]
        bot.send_message(message.from_user.id, weather.getweather(city))
        botan.track(config.botan_key, message.chat.id, message, 'Погода')
        return
    elif message.text == "привет, как тебя зовут?":
        bot.send_message(message.from_user.id, 'робот я')
        botan.track(config.botan_key, message.chat.id, message, 'text')
        return
# Если пользователь отправил "и чо?" отвечаем "да ничо"
    elif message.text == "и чо?":
        bot.send_message(message.from_user.id, 'да ничо')
        botan.track(config.botan_key, message.chat.id, message, 'text')
        return


#Если пользователь отправил слово/фразу, на которое(ую) нет ответа
    else:
        bot.send_message(message.from_user.id, "Извините, я Вас не понимаю")
        botan.track(config.botan_key, message.chat.id, message, 'text')
        return
Esempio n. 2
0
def send_sms():
    account_sid = "account"
    auth_token = "token"

    client = Client(account_sid, auth_token)

    client.api.account.messages.create(
        to="+number",
        from_="+number",
        body=weather.getweather(45.4215, -75.6972))
def weather(**args):  # O(n), n is the getweather complexity.
    '''
    Commits the command "weather".

    args is a dict with args and values.
    '''
    if all(keys not in ['id', 'units'] for keys in args):
        raise CommandError('Wrong arguments', 'weather')
    return getweather(Location(int(args['id'])),
                      units=args['units'] if 'units' in args else 'c')
Esempio n. 4
0
 def POST(self):
     #从获取的xml构造xml dom树
     str_xml = web.data()	#获取post来的数据
     xml = etree.fromstring(str_xml)	#进行XML解析
     #提取信息
     #content = xml.find("Content").text
     msgtype = xml.find("MsgType").text
     fromUser = xml.find("FromUserName").text
     toUser = xml.find("ToUserName").text
     mc = pylibmc.Client() #初始化一个memcache实例用来保存用户的操作
     if msgtype == "event":
         mscontent = xml.find("Event").text
         if mscontent == "subscribe":
             replyText = u'欢迎关注kaiyao机器人!\n------------------------输入help获取操作指南'
             return self.render.reply_text(fromUser,toUser,int(time.time()),replyText)
         if mscontent == "unsubscribe":
             replyText = u'欢迎您以后再来!!'
             return self.render.reply_text(fromUser,toUser,int(time.time()),replyText)
     
     if msgtype == 'text':
         content = xml.find("Content").text
         if content.lower() == 'bye':
             mc.delete(fromUser+'_xhj')
             return self.render.reply_text(fromUser,toUser,int(time.time()),u'从小黄鸡模式中跳出\n------------------------ \n输入help获取操作指南')
         if content.lower() == 'xhj':
             mc.set(fromUser+'_xhj','xhj')
             return self.render.reply_text(fromUser,toUser,int(time.time()),u'进入小黄鸡模式,聊天吧\n输入bye跳出小黄鸡模式')
         
         #读取memcache中的缓存数据
         mcxhj = mc.get(fromUser+'_xhj')
         
         if mcxhj == 'xhj':
             res = xiaohuangji(content)
             reply_text = res['response']
             if u'微信' in reply_text:
                 reply_text = u"小黄鸡脑袋出问题了,请换个问题吧~"
             return self.render.reply_text(fromUser,toUser,int(time.time()),reply_text)
         
         if content.lower() == 'joke':
             joke_info = joke.getjoke()
             return self.render.reply_text(fromUser,toUser,int(time.time()),joke_info)
         
         if content == 'help':
             replyText = u'''------------------------\n直接输入中英文返回其对应英中翻译\n------------------------\n输入xhj进入小黄鸡模式\n------------------------\n输入'weather+地名'进行天气查询\n------------------------\n输入joke获取一段笑话\n------------------------\n其余功能开发中......'''
             return self.render.reply_text(fromUser,toUser,int(time.time()),replyText)
         if content.startswith('weather'):
             city = content[8:]
             city = city.encode('utf-8')
             weather_info = weather.getweather(city)
             return self.render.reply_text(fromUser,toUser,int(time.time()),weather_info)
         elif type(content).__name__ == "unicode":
             content = content.encode('utf-8')
         Nword = trans.youdao(content)
         return self.render.reply_text(fromUser,toUser,int(time.time()),Nword)
Esempio n. 5
0
def capture():
    os.system('fswebcam image.jpeg')  #replace with Picam command
    sleep(5)
    w = getweather("DELHI", "cbbe618c3e4f5c2be6ca3e7c4efc8e0d")
    files = {'file1': open('image.jpeg', 'rb')}
    d, t = w.descntemp()
    r = requests.post('http://ootoday.herokuapp.com/uploadnew.php',
                      data={'weather': d},
                      files=files)
    id = r.json()['id']
    pickle.dump(id, open("id.pickle", 'wb'))
    return "capture stored"
Esempio n. 6
0
 def get(self, input_city):
     try:
         if re.match('^[a-zA-Z]+$', input_city):
             local = input_city
         else:
             local='beijing'
     except:
         local = 'beijing'
     text = weather.getweather(local).split('\n')
     today = text[0][0:text[0].index(' ')]
     today_situation = text[1]
     today_temperature = text[2]
     tomorrow = text[4][0:text[4].index(' ')]
     tomorrow_situation = text[5]
     tomorrow_temperature = text[6]
     self.write(json.dumps({'today': today,
                            'today_situation': today_situation,
                            'today_temperature': today_temperature,
                            'tomorrow': tomorrow,
                            'tomorrow_situation': tomorrow_situation,
                            'tomorrow_temperature': tomorrow_temperature}, ensure_ascii=False))
Esempio n. 7
0
def index():
    w = getweather("DELHI", "cbbe618c3e4f5c2be6ca3e7c4efc8e0d")
    d, t = w.descntemp()
    t = roundUp(float(t), 1)
    return render_template("index.html", desc=d, temp=t)
Esempio n. 8
0
def local_weather(word, word_eol, userdata):
        response = weather.getweather(word_eol[1])
        print response
Esempio n. 9
0
def get_weather(lookup, destination):
    response = weather.getweather(lookup)
    destination.command("say " + str(response))
Esempio n. 10
0
def local_weather(word, word_eol, userdata):
    response = weather.getweather(word_eol[1])
    print response
Esempio n. 11
0
def get_weather(lookup, destination):
    response = weather.getweather(lookup)
    destination.command("say " + str(response))
Esempio n. 12
0
 def on_message(self, message):
     mname = SocketHandler.get_name(self)
     if re.search('^```.*```', str(message).encode('utf-8'),re.S):
         message=markdown.markdown(message,extensions=['markdown.extensions.extra','markdown.extensions.codehilite'])
         message_json=SocketHandler.get_json(self,'user',id(self),0,mname,1,message)
         SocketHandler.send_to_all(self,message_json)
     elif re.search('^\$\$.*\$\$',str(message).encode('utf-8'),re.S):
         message = message.strip()
         message = '<img src="https://latex.codecogs.com/gif.latex?{0}" style="border:none;">'.format(message[2:-2])
         message_json=SocketHandler.get_json(self,'user',id(self),0,mname,2,message)
         SocketHandler.send_to_all(self,message_json)
     elif re.search('^/weather',str(message).encode('utf-8'),re.S):
         try:
             local = message[message.index(' ')+1:]
         except:
             local='beijing'
         message_bot = "%s's weather:<br>"%(local)+weather.getweather(local).replace('\n','<br>')
         message_json=SocketHandler.get_json(self,'user',id(self),1,mname,3,message)
         SocketHandler.send_to_all(self,message_json)
         message_json=SocketHandler.get_json(self,'bot',id(self)+12138,0,'Weather robot',3,message_bot)
         SocketHandler.send_to_all(self,message_json)
     elif re.search('^/news',str(message).encode('utf-8'),re.S):
         message_bot = 'Today News:<br>'+news.getnews().replace('\n','<br>')
         message_json=SocketHandler.get_json(self,'user',id(self),1,mname,3,message)
         SocketHandler.send_to_all(self,message_json)
         message_json=SocketHandler.get_json(self,'bot',id(self)+12138,0,'News robot',3,message_bot)
         SocketHandler.send_to_all(self,message_json)
     elif re.search('^/help',str(message).encode('utf-8'),re.S):
         message_json=SocketHandler.get_json(self,'user',id(self),1,mname,3,message)
         self.write_message(json.dumps(message_json))
         message='''使用帮助:<br>本聊天室规定使用Enter换行,Ctrl+Enter发送
                             <br>支持markdown语法发送<strong>代码</strong><br>Example:
                             <br>```python<br>print('Hello world!')<br>```
                             <br>支持使用LaTeX语法发送<strong>公式</strong><br>Example:<br>$$h = \\frac{1}{2}gt^2$$
                             <br>支持使用<strong>/weather 地点(拼音)</strong>查看天气
                             <br>支持使用<strong>/news</strong>查看新闻
                             <br>如果有什么建议,欢迎使用<strong>/feedback 内容</strong>给我们反馈'''
         message_json=SocketHandler.get_json(self,'bot',id(self)+12138,0,'Master robot',3,message)
         self.write_message(json.dumps(message_json))
     elif re.search('^/feedback',str(message).encode('utf-8'),re.S):
         cleaner = lxml.html.clean.Cleaner(style=True, scripts=True, frames = True,
                                           forms = True,page_structure=False, safe_attrs_only=False)
         message = cleaner.clean_html(message)
         feedback = message[13:-4]
         user_agent = self.request.headers['user-agent'].replace("\'","|")
         ip = self.request.headers.get("X-Real-IP")
         cx = MySQLdb.connect("localhost", "chat", "chat123", "chat",charset='utf8')
         cx.set_character_set('utf8')
         cursor = cx.cursor()
         cursor.execute("insert into feedback (id,ip,user_agent,time,message) values (%d,'%s','%s','%s','%s')"%(id(self),ip,user_agent,time.strftime("%H:%M:%S", time.localtime()),feedback))
         cursor.close()
         cx.commit()
         cx.close()
         message_json=SocketHandler.get_json(self,'user',id(self),1,mname,3,message)
         self.write_message(json.dumps(message_json))
         message='我们已经收到你的反馈了,谢谢你!'
         message_json=SocketHandler.get_json(self,'bot',id(self)+12138,0,'Master robot',3,message)
         self.write_message(json.dumps(message_json))
     elif message == 'c93c60882b37254bb13e80183f291af3':
         pass
     else:
         message = message.replace('\n','<br>')
         cleaner = lxml.html.clean.Cleaner(style=True, scripts=True, frames = True,
                                           forms = True,page_structure=False, safe_attrs_only=False)
         message = cleaner.clean_html(message)
         message_json=SocketHandler.get_json(self,'user',id(self),0,mname,3,message)
         SocketHandler.send_to_all(self,message_json)
Esempio n. 13
0

_user = ""
_pwd  = ""
_to   = ""
# _to   = "*****@*****.**"
file_name = "/chat/static/images/bg-main.jpg" 

pro = random.randint(1, 280)
# url = 'https://ky.crazyc.cn/proverb/%d'%(pro)
# req = urllib2.Request(url)
# res_data = urllib2.urlopen(req)
# res = res_data.read()
# res = json.loads(res)

weather_data = weather.getweather()

#使用MIMEText构造符合smtp协议的header及body
#下面构造网页
mail_msg = """
<html>
	<body>
		<h4>{10}今天的天气</h4>
		<p>空气质量:{0},空气质量指数:{1},PM2.5:{2}</p>
		<p>实时天气:{3},最高温度:{4}℃,最低温度:{5}℃</p>
		<p>{6}</p>
		<p>风向:{7},风力:{8}级</p>
		<hr/>
		<h4>今天的新闻头条</h4>
		{9}
	</body>
Esempio n. 14
0
from speech import speech
from spotify_playback_control import *
from weather import getweather
from translate import *
from News import *

temp_status = False
if playing_status() == True:
    temp_status = playing_status()
    spotifycontrol("暫停")
command = speech("嗨!", 2, 1)
if command == "音樂":
    subcommand = speech("請輸入指令:", 2, 2)
    if temp_status == True:
        resume()
    spotifycontrol(subcommand)
elif command == "翻譯":
    translate(speech('請選擇要翻譯的語言', 2, 3), speech('正在翻譯...', 2, 2))
    if temp_status == True:
        resume()
elif command == "天氣":
    getweather()
    if temp_status == True:
        resume()
elif command == "新聞":
    post(speech('請選擇搜尋方式', 2, 2))
    if temp_status == True:
        resume()
else:
    print("...")