def google(message): ''' 得到用户输入的内容,将google api 返回的结果发送给用户 ''' google_rs_message = '' rs = google_api(message)['responseData']['results'] for _ in rs[:1]: google_rs_message += "{}\n{}".format(_['url'].encode('utf-8'), _['content'].encode('utf-8')) sendMessage(chat_id, str(google_rs_message))
def nasa_pic(message): ''' 同上 ''' rs = nasa_api(message) if 'error' in rs: sendMessage(chat_id, rs['error']) else: nasa_pic_and_explanation = "{}".format(rs['url']) sendMessage(chat_id, nasa_pic_and_explanation)
def chore_switch(): members = getMembers() conn = create_conn() cur = conn.cursor() query = "SELECT name FROM chore_assignment" cur.execute(query) past_assignment = cur.fetchall() query = "SELECT name, num_helper FROM chores" cur.execute(query) chore_list = cur.fetchall() if past_assignment: # if a member from the previous week's assignment is still in the chat, add that member to curMembers curMembers = [] for person in past_assignment: if person[0] in members: curMembers.append(person[0]) # remove duplicates members = [] for person in curMembers: if person not in members: members.append(person) # reorder curMember list member = members[0] members.remove(member) members.append(member) query = "DELETE FROM chore_assignment" cur.execute(query) conn.commit() index = 0 count = 0 for chore in chore_list: name = chore[0] num_helper = int(chore[1]) count += num_helper while num_helper > 0: query = "INSERT INTO chore_assignment(name, chore) VALUES('" + members[ index] + "', '" + name + "')" cur.execute(query) conn.commit() index = increment(index, len(members)) num_helper -= 1 while count % len(members): query = "INSERT INTO chore_assignment(name, chore) VALUES('" + members[ index] + "', 'NULL')" cur.execute(query) conn.commit() index = increment(index, len(members)) count += 1 message = '' for member in members: query = "SELECT chore FROM chore_assignment WHERE name = '" + member + "'" cur.execute(query) results = cur.fetchall() message += member + ': ' for chore in results: message += chore[0] + '\n' sendMessage("The chore assignment for this week is as below:\n" + message) conn.close()
def webhook(): data = request.get_json() text = data['text'].split(' ') command = text[0] if command == '/add': num_helper = text[len(text) - 1] if len(text) == 3: chore = text[1] else: chore = ' '.join(text[1:len(text) - 1]) conn = create_conn() cur = conn.cursor() query = "INSERT INTO chores(name, num_helper) VALUES('" + chore + "', '" + num_helper + "')" cur.execute(query) conn.commit() conn.close() sendMessage(chore.upper() + " with " + num_helper + " helper(s) has been added to your chore list.") elif data['text'] == '/show chore list': conn = create_conn() cur = conn.cursor() query = "SELECT id, name, num_helper FROM chores" cur.execute(query) results = cur.fetchall() conn.close() if not results: sendMessage("Chore list is empty.") else: message = '' for entry in results: message += str(entry[0]) + '. ' + entry[1].upper( ) + '\nNumber of helpers: ' + str(entry[2]) + '\n' sendMessage(message) elif command == '/delete': conn = create_conn() cur = conn.cursor() query = "SELECT name FROM chores WHERE id = " + text[1] cur.execute(query) results = cur.fetchall() if not results: sendMessage("Oops! chore does not exist.") else: chore = results[0][0] query = "DELETE FROM chores WHERE id = " + text[1] cur.execute(query) query = "DELETE FROM chore_assignment WHERE chore = '" + chore + "'" cur.execute(query) conn.commit() conn.close() message = chore.upper() + " has been removed from the chore list." sendMessage(message) elif command == '/reset': id = text[1] new_num = text[2] conn = create_conn() cur = conn.cursor() query = "SELECT name FROM chores WHERE id = " + id cur.execute(query) results = cur.fetchall() if not results: sendMessage("Oops! Chore does not exist.") else: chore = results[0][0] query = "UPDATE chores SET num_helper = " + new_num + " WHERE id = " + id cur.execute(query) conn.commit() conn.close() message = chore.upper( ) + " will need " + new_num + " helper(s) from now on!" sendMessage(message) elif data['text'] == '/our chores': conn = create_conn() cur = conn.cursor() members = getMembers() message = '' for member in members: query = "SELECT chore FROM chore_assignment WHERE name = '" + member + "'" cur.execute(query) results = cur.fetchall() if not results: sendMessage("No chores have been assigned yet.") break else: message += member + ': ' for chore in results: message += chore[0] + '\n' sendMessage("The chore assignment for this week is as below:\n" + message) elif data['text'] == '/my chore': conn = create_conn() cur = conn.cursor() query = "SELECT chore FROM chore_assignment WHERE name = '" + data[ 'name'] + "'" cur.execute(query) results = cur.fetchall() if not results: sendMessage("No chores have been assigned to you yet.") else: message = '' for chore in results: message += chore[0] + '\n' sendMessage("This week you are responsible for " + message) return data['text']
def main(): ''' 用getUpdate方法,获取bot的消息列表 ''' updates = getUpdates() rs = updates["result"] global update_id_deque ''' update_id_deque每次都append,消息列表中最后一条信息的update_id,其中update_id是 自增长的,bot每收到一条消息,update_id都会加1,如果没有收到新消息,则update_id不变, 将update_id放入update_id_deque的目的是,通过计算update_id_deque[0]和update_id_deque[1] 的差,可以知道是否收到了新消息。 ''' update_id_deque.append(rs[-1]['update_id']) ''' update_id_deque长度为1时不做任何处理,这中情况出现在程序刚运行时 ''' if len(update_id_deque) == 1: pass ''' update_id_deque长度为2时,求出这个[1]与[0]之差 若差是0,这说明没有收到新的消息, 若差不是0,这说明收到了新的消息,由于我是间隔一定时间运行一次main函数,在这间隔期间 有可能收到不止一条消息。 :param delta: 则告诉你期间一共收到多少条消息 :param message_text: 接收到的消息 如果收到的消息以 /g开头,则执行google函数,返回json /trans开头,则执行translate函数,返回json /nasa开头,则执行nasa_pic函数,返回json /help开头,则直接发送消息给用户 ''' if len(update_id_deque) == 2: print("len is 2") delta = update_id_deque[1] - update_id_deque[0] if delta != 0: for _ in rs[-delta:]: message_text = _['message']['text'] if message_text.startswith('/g'): global chat_id chat_id = _['message']['chat']['id'] google(message_text[3:]) update_id_deque.append(rs[-1]['update_id']) elif message_text.startswith('/trans'): chat_id = _['message']['chat']['id'] translate(message_text[7:]) update_id_deque.append(rs[-1]['update_id']) elif message_text.startswith('/nasa'): chat_id = _['message']['chat']['id'] if len(message_text.strip()) == 5: nasa_pic(message=None) else: nasa_pic(message_text[6:]) update_id_deque.append(rs[-1]['update_id']) elif message_text.startswith('/help'): chat_id = _['message']['chat']['id'] help_message = str("命令列表:\n \ * /g <关键词> google搜索 \n \ * /trans <翻译的内容> \n \ * /nasa [日期(若不填,默认为美国时间当日, 格式如2015-08-03)]") sendMessage(chat_id, help_message)
def translate(message): ''' 同上,不同的api,返回结果不同,如何处理需要查看它返回的json格式 ''' rs = youdao_api(message) if rs['errorCode'] == 0: if 'basic' in rs: translate_rs_message = "{}\n{}".format(rs['translation'][0].encode('utf-8'), rs['basic']['explains'][0].encode('utf-8')) else: translate_rs_message = "{}".format(rs['translation'][0].encode('utf-8')) sendMessage(chat_id, str(translate_rs_message)) elif rs['errorCode'] == 20: sendMessage(chat_id, u"要翻译的文本过长") elif rs['errorCode'] == 30: sendMessage(chat_id, u"无法进行有效的翻译") elif rs['errorCode'] == 40: sendMessage(chat_id, u"不支持的语言类型") elif rs['errorCode'] == 50: sendMessage(chat_id, u"无效的key") elif rs['errorCode'] == 60: sendMessage(chat_id, u"无词典结果,仅在获取词典结果生效")
import argparse import time from helper import validMessage, sendMessage, getScores, generateMessageData parser = argparse.ArgumentParser() parser.add_argument('--id', '-id', default=2730, help='enter the series id/match id') args = parser.parse_args() while (True): time.sleep(5) venue, status, summary, scores = generateMessageData(args) test = sendMessage(venue) time.sleep(1) test = sendMessage(status) time.sleep(1) test = sendMessage(summary) time.sleep(1) message = getScores(scores) test = sendMessage(validMessage(message)) #test_id = 49839, 2730 #test_id_3rd_T20 = 49844, 2731 #1 Print scores^ #2 Isolate the functions; this main.py should call other functions^ #3 make another function to send the notifs: shouldn't be happening in while loop* #4 more functionalities
import argparse import time from helper import trialMatch3rdT20, sendMessage, scorecardDetails parser = argparse.ArgumentParser() parser.add_argument('--seriesId', '-seriesId', default=2731, help='enter the series id') parser.add_argument('--matchId', '-matchId', default=49845, help='enter the match id') args = parser.parse_args() while (True): time.sleep(5) summary = trialMatch3rdT20(args) batsmen, bowler, MOTM = scorecardDetails(args) test = sendMessage(summary) test = sendMessage( "Best Batsmen: {} \nBest Bowler: {} \nMan ff The Match: {}".format( batsmen, bowler, MOTM)) time.sleep(1) #test_id = 49839, 2730 #test_id_3rd_T20 = 49844, 2731