def OnInit(self): #初始化数据库链接 self.db = sqlite3.connect(opj("data/test.db")) self.conn = self.db.cursor() self.isOnline = False; #联网状态 #打印小票 # self.pdata = wx.PrintData() # self.pdata.SetPaperId(wx.PAPER_LETTER) # self.pdata.SetOrientation(wx.PORTRAIT) # data = wx.PrintDialogData(self.pdata) # printer = wx.Printer(data) # ConfigData=[(u'\u5c0f\u6e14\u6751\u7f8e\u98df\u5e7f\u573a', u'\u5c0f\u6e14\u6751\u5bf9\u8d26\u5355', u'\u5c0f\u6e14\u6751\u6b22\u8fce\u60a8 !\u7535\u8bdd 0576-88678777', u'\u53f0\u5dde\u5c0f\u6e14\u6751\u5eb7\u5e73\u8def\u5e97,\u6b22\u8fce\u60a8\u7684\u5149\u4e34')] # goodsData=[{u'\u5546\u54c1\u7f16\u7801': u'0005', u'\u6298\u6263': u'0.98', u'\u5355\u4ef7': u'200.01', u'\u91d1\u989d': u'196.01', u'\u5546\u54c1\u6761\u7801': u'1', u'\u5355\u4f4d': u'\u4ef6', u'\u5546\u54c1\u540d\u79f0': u'\u516d\u795e\u6e05\u51c9\u723d\u80a4\u6c90\u6d74\u9732200ml', u'\u6570\u91cf': u'1'}, {u'\u5546\u54c1\u7f16\u7801': u'012205', u'\u6298\u6263': u'0.99', u'\u5355\u4ef7': u'159.05', u'\u91d1\u989d': u'314.92', u'\u5546\u54c1\u6761\u7801': u'2', u'\u5355\u4f4d': u'\u4ef6', u'\u5546\u54c1\u540d\u79f0': u'\u516d\u795e\u827e\u53f6\u5065\u80a4\u6c90\u6d74\u9732\uff08\u6e05\u51c9\u578b\uff09450ml', u'\u6570\u91cf': u'2'}, {u'\u5546\u54c1\u7f16\u7801': u'13213', u'\u6298\u6263': u'0.1', u'\u5355\u4ef7': u'12.05', u'\u91d1\u989d': u'2.41', u'\u5546\u54c1\u6761\u7801': u'3', u'\u5355\u4f4d': u'\u7bb1', u'\u5546\u54c1\u540d\u79f0': u'\u5546\u54c1233', u'\u6570\u91cf': u'2'}] # OtherData = ['2015111916345658', u'196.0',u"想想想"] # printout = Print.GoodsPrinter(ConfigData,goodsData, u"小票打印",OtherData) # printer.Print(None,printout,True) self.Storeid='2' self.Id="111"; self.Name="222" # self.LogIn=False; # self.doLogIn(); # if(not self.LogIn): # #如果未登录 关闭数据库链接,退出App # return False; data={"storeid":self.Storeid} rs=Http.sendHttp(Http.Action_getOffInfo,data) if(not rs==""): ## #删除数据库特价商品 sql='delete from sale_offprice ' Utils.commit(sql,None) goodsRs=rs['data'] if(len(goodsRs)>0): for i in range(0, len(goodsRs)) : print(goodsRs[i]) sql = 'insert into sale_offprice (goodsId,barCode,offprice,begindate,enddate,begintime,endtime) values (?,?,?,?,?,?,?)' Utils.commit(sql,(goodsRs[i]['goodsid'],goodsRs[i]['barcode'],goodsRs[i]['retailprice'],goodsRs[i]['begindate'],goodsRs[i]['enddate'],goodsRs[i]['begintime'],goodsRs[i]['endtime'],)) if(self.isOnline): #联网状态 data={"storeid":self.Storeid} rs=Http.sendHttp(Http.Action_getOffInfo,data) if(not rs==""): ## #删除数据库特价商品 sql='delete from sale_offprice ' Utils.commit(sql,None) goodsRs=rs['data'] if(len(goodsRs)>0): for i in range(0, len(goodsRs)) : print(goodsRs[i]) sql = 'insert into sale_offprice (goodsId,barCode,offprice,begindate,enddate,begintime,endtime) values (?,?,?,?,?,?,?)' Utils.commit(sql,(goodsRs[i]['goodsid'],goodsRs[i]['barcode'],goodsRs[i]['retailprice'],goodsRs[i]['begindate'],goodsRs[i]['enddate'],goodsRs[i]['begintime'],goodsRs[i]['endtime'],)) #初始化Frame self.Homeframe=Frames.HomeFrame() return True
def test_co(access_token: str, protocole: str, users: list, passwords: list): """Test the server provided in access_token with every user""" global LOGGER if protocole == 'ftp': Ftp.ftp_test(LOGGER, access_token, users, passwords) if protocole == 'http': Http.http_test(LOGGER, access_token, users, passwords) if protocole == 'ssh': Ssh.ssh_test(LOGGER, access_token, users, passwords) if protocole == 'sftp': Ssh.ssh_test(LOGGER, access_token, users, passwords, True)
def logOut(url, headers="", userId="", interfaceName="", printLogs=0): params = {"userId": userId} res = Http.get(url, headers=headers, interfaceName=interfaceName, logs=printLogs) return res
def fetchActiveUsers(bot, all_employees): # Check for new members params = {"token": USER_TOKEN_STRING, "channel": bot.channel_id} response = requests.get("https://slack.com/api/channels.info", params=params) print "fetchActiveUsers response: " + response.text parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: user_ids = parsed_message["channel"]["members"] active_users = [] for user_id in user_ids: # Don't add hudl_workout if user_id != bot.user_id: # Add user to the cache if not already if user_id not in bot.user_cache: bot.user_cache[user_id] = User(user_id, all_employees) if not bot.first_run: # Push our new users near the front of the queue! bot.user_queue.insert(2,bot.user_cache[user_id]) if bot.user_cache[user_id].isActive(): active_users.append(bot.user_cache[user_id]) if bot.first_run: bot.first_run = False return active_users
def addComment(url, headers="", datas=""): # datas={'combody':combody,'whetherremind':False} res = Http.post(url, headers=headers, datas=json.dumps(datas), interfaceName="addComment") return res
def getAccountsOfUser(url, headers, params="", interfaceName="", printLogs=0): res = Http.get(url, headers, params=params, interfaceName=interfaceName, logs=printLogs) return res
def createFollow(url, headers="", datas="", interfaceName="", printLogs=0): res = Http.post(url, headers=headers, datas=json.dumps(datas), interfaceName=interfaceName, logs=printLogs) return res
def getFollowsnew(url, headers="", datas="", interfaceName="", printLogs=0): res = Http.get(url, headers=headers, datas=json.dumps(datas), interfaceName=interfaceName, logs=printLogs) return res
def getCommissions(url, headers="", params="", interfaceName="", printLogs=1): res = Http.get(url, headers=headers, params=params, interfaceName=interfaceName, logs=printLogs) return res
def get_json(page: int, tag_on, tags: str): """ 获取列表页的json数据 :param page: 页码 :type page: int :param tag_on: tag搜索开关 :type tags: str :return: str """ if tag_on: url = 'https://yande.re/post.json?tags={}&page={}'.format( tags, str(page)) else: url = 'https://yande.re/post.json?page=' + str(page) #JSON API json_data = Http.get(url) if not json_data: print('请求 ' + url + ' 失败') exit() try: json_data = json_data.decode('utf-8') except: print(url + ' 解码失败') exit(500) return json_data
def getSpecialAccountIndex(headers="", brokerID=3, accountType=1,interfaceName="getAccounts", printLogs=1): res = Http.get(userData['hostName'] + userDataAccount['getAccounts_url'] + userDataAccount['getAccounts_url2'], headers=headers,interfaceName=interfaceName,logs=printLogs) resList = [] for tuple in json.loads(res.text)['data']['accounts']: if tuple['BrokerId'] == brokerID and tuple['AccountType'] == accountType: resList.append(str(tuple['AccountIndex'])) return resList
def jydssignin(url, headers="", datas="", interfaceName="", printLogs=0): res = Http.post(url, headers=headers, datas=json.dumps(datas), interfaceName=interfaceName, logs=printLogs) return res
def clear_trojan_rule(): trojan_rule_url = Config.get_config_values('TrojanRule', 'url') trojan_result = Http.http_get(trojan_rule_url) res_json = json.loads(trojan_result, encoding="utf-8") for index in range(len(res_json)): #print hjons[index]['nickname'] scan_trojan(res_json[index]['content'], res_json[index]['route'])
def getTraders(url, headers="", params="", interfaceName="", printLogs=0): res = Http.get(url, headers=headers, params=params, interfaceName=interfaceName, logs=printLogs) return res
def getHomeFollower(url, headers="", params="", interfaceName="", printLogs=0): res = Http.get(url, headers=headers, params=json.dumps(params), interfaceName=interfaceName, logs=printLogs) return res
def getUserID(url="", headers="", params="", interfaceName="", printLogs=1): res = Http.get(userData['hostName'] + userData['getTraders_url'], headers=headers, params=params, interfaceName=interfaceName, logs=printLogs) return json.loads(res.text)['data']['items'][0]['UserId']
def getMyFans(url, datas="", headers=""): # datas = {"pageIndex": pageIndex, "pageSize": pageSize} res = Http.get(url, headers=headers, params=json.dumps(datas), interfaceName="getMyFans") return res
def getUserPraiseMicroBlogs(url, datas="", headers=""): # datas={'id':id,'top':top,'authorId':authorId} res = Http.get(url, params=json.dumps(datas), headers=headers, interfaceName="getUserPraiseMicroBlogs") return res
def applyCommission(url, headers="", interfaceName="", datas="", printLogs=0): res = Http.post(url, headers=headers, interfaceName=interfaceName, datas=json.dumps(datas), logs=printLogs) return res
def blogShare(url, headers="", datas=""): # datas={'blogId':blogId} res = Http.get(url, headers=headers, params=json.dumps(datas), interfaceName="blogShare") return res
def doLogIn(self): #登陆方法 self.Dlg_LogIn = self.showDialogWithErrorMsg("") while (not self.LogIn): val = self.Dlg_LogIn.ShowModal() if val == wx.ID_OK: self.Dlg_LogIn.Destroy();#返回结果 关闭对话框 username=self.Dlg_LogIn.GetValue()[0]; password=self.Dlg_LogIn.GetValue()[1]; if(username==u'' or password==''): self.showDialogWithErrorMsg(u"用户名或密码不能为空") else : data={"username":username,"password":password,"type":"client"} rs=Http.sendHttp(Http.Action_signIn,data) if(not rs==""): #rs不为空,说明是请求成功并且返回数据 if(not rs['flag']): self.showDialogWithErrorMsg(rs['msg']) else: #账号密码正确 self.doAfterLogIn(rs['userid'],rs['name']) self.isOnline=True; self.CheckTime() else : #rs为空,说明是断网状态或服务器有问题,查询本地数据库 self.conn.execute("select id,name,password from sys_user where username= ? ",(username,)) res =self.conn.fetchall() if(not len(res)>0): self.showDialogWithErrorMsg(u"用户名不存在") else: m1=md5.new() md5psw=m1.update(password) if(res[0][2]==m1.hexdigest()): self.doAfterLogIn(res[0][0],res[0][0]) else: self.showDialogWithErrorMsg(u"账号或密码错误") if val == wx.ID_CANCEL: return;
def getMyBlogList(url, datas="", headers=""): # datas = {"pageIndex": pageIndex, "pageSize": pageSize,'startId':startId} res = Http.get(url, headers=headers, params=datas, interfaceName="getMyBlogList") return res
def download(post): file_name = Function.rename(Http.decode(post['file_url'])) add_log('{} 开始下载p{} 大小{}M 类型{}'.format( time.strftime('%H:%M:%S'), post['id'], "%.2f" % (post['file_size'] / 1048576), post['file_ext'])) ts = time.time() img = Http.get( post['file_url'], { 'Host': 'files.yande.re', 'Referer': 'https://yande.re/post/show/' + post['id'] }) cost_time = time.time() - ts add_log('{}下载完毕,耗时{}s,平均速度{}k/s'.format( post['id'], "%.2f" % cost_time, "%.2f" % (post['file_size'] / 1024 / cost_time))) Function.write(folder_path, file_name, img)
def singleFileUpload(url, headers="", datas="", interfaceName="", printlogs=0): res = Http.post(url, headers=headers, datas=datas, interfaceName=interfaceName, logs=printlogs) return res
def upload(url, headers="", datas="", interfaceName="addBlog", printLogs=0): res = Http.post(url, headers=headers, datas=json.dumps(datas), interfaceName=interfaceName, logs=printLogs) return res
def updateFollow(url, traderindex="", headers="", datas="", interfaceName="", printLogs=0): res = Http.put(url + traderindex, headers=headers, data=json.dumps(datas)) return res
def download(post, folder_path): # 获取文件名 # URL解码 file_name = Http.decode(post['file_url']) file_name = Function.rename(file_name) # 文件是否已存在? if Function.exists(folder_path, file_name): Log.add(post['id'] + ' 已存在,跳过') return True Log.add(time.strftime('%H:%M:%S') + ' 开始下载p' + post['id'] + ' 大小' + str("%.2f" %(post['file_size'] / 1048576)) + 'M 类型' + post['file_ext']) ts = time.time() img = Http.get(post['file_url'], {'Host': 'files.yande.re', 'Referer': 'https://yande.re/post/show/' + post['id']}) cost_time = time.time() - ts Log.add('下载完毕,耗时' + str("%.2f" %cost_time) + 's, 平均速度' + str("%.2f" %(post['file_size'] / 1024 / cost_time)) + 'k/s') Function.write(folder_path, file_name, img)
def test_postShortBlog_002(self): '''发布@用户的微博,检查@我的微博列表''' # 登录被@用户的账号 signinParams = { "account": userData['followAccount'], "password": userData['followPasswd'], "remember": False } singinRes = Auth.signin(userData['hostName'] + authData['signin_url'], datas=signinParams, headers=userData['headers']) self.assertEqual(singinRes.status_code, userData['status_code_200']) atToken = json.loads(singinRes.text)['data']['token'] atHeaders = dict( userData['headers'], **{userData['Authorization']: userData['Bearer'] + atToken}) self.nickName = json.loads(singinRes.text)['data']['nickname'] # self.userId=json.loads(singinRes.text)['data']['id'] '''发布@用户的微博''' params = { 'blogBody': '@' + self.nickName + ' 测试微博@用户的微博', 'blogid': self.blogId, 'haspicture': False, # 是否有图片 有为 true 没有为false 'whetherremind': True, # 发布@用的微博,此项必须为true.是否需要后台额外提醒 需要提醒为 true 否为false 默认为false, 'blogType': 0, # blogType微博类型:0:普通微博;1:公告;2:品种;3:交易动态 'symbol': "" } postShortBlogRes = Social.postShortBlog( userData['hostName'] + socialData['postShortBlog_url'], headers=self.headers, datas=params) self.assertEqual(postShortBlogRes.status_code, userData['status_code_200']) time.sleep(3) #检查@我的微博列表 blogListParams = {'pageIndex': 1, 'pageSize': 10} atMeblogListRes = Http.get(userData['hostName'] + socialData['getAtMeBlogList_url'], headers=atHeaders, params=blogListParams) self.assertEqual(atMeblogListRes.status_code, userData['status_code_200']) atMeBlogId = json.loads( atMeblogListRes.text)['data']['List'][0]['MBlog']['id'] self.assertEqual(self.blogId, atMeBlogId) # 删除微博 delBlogRes = Social.deleteBlog(userData['hostName'] + socialData['deleteBlog_url'] + str(self.blogId), headers=self.headers) self.assertEqual(delBlogRes.status_code, userData['status_code_200']) signout = Auth.signout(userData['hostName'] + authData['signout_url'], datas=atHeaders) self.assertEqual(signout.status_code, userData['status_code_200'])
def getDayAccountMoneyAndEquityList(url, headers="", interfaceName="", printLogs=0): res = Http.get(url, headers=headers, interfaceName=interfaceName, logs=printLogs) return res
def isActive(self): params = {"token": USER_TOKEN_STRING, "user": self.id} response = requests.get("https://slack.com/api/users.getPresence",params=params) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: status = parsed_message["presence"] return status == "active" else: return False
def getFollowerFollowTraderList(url, headers="", interfaceName="", printLogs=0): res = Http.get(url, headers=headers, interfaceName=interfaceName, logs=printLogs) return res
def initiateThrowdown(bot, all_employees, message): text = message['text'].lower() words = text.split() challengerId = message['user'] active_users = fetchActiveUsers(bot, all_employees) challengees = [] challenger = None for user in active_users: if user.id == challengerId: challenger = user break exercise = findExerciseInText(bot, text) exercise_reps = findIntInText(bot, words) if challenger is not None and challenger.has_challenged_today == True: already_challenged_text = 'You can only give out a challenge once a day ' + challenger.real_name requests.post(bot.post_message_URL + "&text=" + already_challenged_text) return if exercise_reps != False and exercise != False and exercise_reps > exercise['maxReps']: too_many_reps_text = 'Please select a number under ' + str(exercise['maxReps']) + ' for that exercise, ' + challenger.real_name requests.post(bot.post_message_URL + "&text=" + too_many_reps_text) return if challenger is not None and exercise != False and exercise_reps != False: for user in active_users: for word in words: if user.id.lower() in word: challengees.append(user) print "Found a challengee" if len(challengees) > 0: for challengee in challengees: challengee.addExercise(exercise, exercise_reps) challenger.has_challenged_today = True challenge_text = "You hear that, " + challengees[0].real_name + "? " + challenger.real_name + " is challenging you, " + str(exercise_reps) + " " + str(exercise["units"]) + " " + exercise['name'] + " now!" response = requests.post(bot.post_message_URL + "&text=" + challenge_text) print "initiateThrowdown response: " + response.text parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: last_message_timestamp = parsed_message["ts"] requests.post("https://slack.com/api/reactions.add?token=" + USER_TOKEN_STRING + "&name=yes&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=no&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=sleeping&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") exercise_obj = Exercises(exercise, exercise_reps, challengees, last_message_timestamp) EXERCISES_FOR_DAY.append(exercise_obj) logExercise(bot,challengees,exercise["name"],exercise_reps,exercise["units"],exercise_obj.time_assigned) print challenge_text
def GetCommissionWithdrawRecord(url, headers="", interfaceName="", printLogs=0): res = Http.get(url, headers=headers, interfaceName=interfaceName, logs=printLogs) return res
def getFollow(url, traderindex="", accountIndex="", headers="", interfaceName="", printLogs=0): res = Http.get(url + traderindex + userData['accountIndex'] + str(accountIndex), headers=headers) return res
def setRiskControlForTrader(url, headers, datas="", interfaceName="", printLogs=0): res = Http.put(url, headers=headers, datas=json.dumps(datas), interfaceName=interfaceName, logs=printLogs) return res
def CheckTime(self): #校验时间提醒 客户端时间与系统时间超过1小时时登陆成功会提醒 rs=Http.sendHttp(Http.Action_getDate,None) if(not rs==""): fmt='%Y-%m-%d %H:%M:%S' hourCheckNum = 1 now = datetime.datetime.now() end = (now + datetime.timedelta(hours=hourCheckNum)).strftime(fmt) start = (now - datetime.timedelta(hours=hourCheckNum)).strftime(fmt) now = now.strftime(fmt) if(Utils.compare_time(now,start,end,fmt)): #当前时间与服务器时间超过1小时 wx.MessageBox(u"为正常使用系统,请调整系统时间 ", u"提醒",wx.OK | wx.ICON_ASTERISK)
def fetchNames(self): params = {"token": USER_TOKEN_STRING, "user": self.id} response = requests.get("https://slack.com/api/users.info", params=params) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: user_obj = parsed_message["user"] username = user_obj["name"] real_name = user_obj["profile"]["real_name"] return username, real_name
def announceExercise(bot, minute_interval): exercise = selectExercise(bot) # Announcement String of next lottery time lottery_announcement = "NEXT LOTTERY FOR " + exercise["name"].upper() + " IS IN " + str(minute_interval) + (" MINUTES" if minute_interval != 1 else " MINUTE") # Announce the exercise to the thread if not bot.debug: response = requests.post(bot.post_message_URL + "&text=" + lottery_announcement) print "announceExercise response: " + response.text if bot.last_listen_ts == '0': parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: bot.last_listen_ts = parsed_message["ts"] print lottery_announcement return exercise
def start(self): self.log.info("-- Web Crawler Server Started --") server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((self.host, self.port)) server.listen(10) while not self.serverShutdown: conn, addr = server.accept() self.log.info("Socket Connection accept") http = Http.getRequest(conn) self.log.info("Request URI_STRING", http) if not http.has_key('GET'): conn.close() continue try: Thread(target=self.parseRequests, args=(http, conn)).start() except Exception, errtxt: print errtxt
def listenForReactions(bot): if not bot.debug: for exercise in EXERCISES_FOR_DAY: timestamp = exercise.timestamp response = requests.get("https://slack.com/api/reactions.get?token=" + USER_TOKEN_STRING + "&channel=" + bot.channel_id + "&full=1×tamp=" + timestamp) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: reactions = parsed_message["message"]["reactions"] for reaction in reactions: if reaction["name"] == "yes": users_who_have_reacted_with_yes = reaction["users"] elif reaction["name"] == "no": users_who_have_reacted_with_no = reaction["users"] elif reaction["name"] == "sleeping": users_who_have_reacted_with_sleeping = reaction["users"] for user in exercise.users: if user.id in users_who_have_reacted_with_yes and user not in exercise.completed_users: exercise_name = exercise.exercise["name"] print user.real_name + " has completed their " + exercise_name + " after " + str((time.time() - exercise.time_assigned)) + " seconds" exercise.count_of_acknowledged += 1 exercise.completed_users.append(user) if bot.database: query = dict(username='******'+user.username, exercise=exercise_name, assigned_at=exercise.time_assigned, completed_at=time.time()) bot.db.complete(query) elif user.id in users_who_have_reacted_with_no and user not in exercise.refused_users and user not in exercise.completed_users: exercise_name = exercise.exercise["name"] print user.real_name + " refuses to complete their " + exercise_name exercise.refused_users.append(user) exercise.count_of_acknowledged += 1 elif not isReminderInReminderList(user.id, exercise) and user.id in users_who_have_reacted_with_sleeping: exercise.snoozed_users.append(Reminder(timestamp, datetime.datetime.now(), user, exercise)) if exercise.count_of_acknowledged == len(exercise.users): EXERCISES_FOR_DAY.remove(exercise) print "Removing Exercise"
def listenForCommands(bot, all_employees): response = requests.get("https://slack.com/api/channels.history?token=" + USER_TOKEN_STRING + "&channel=" + bot.channel_id + "&oldest=" + bot.last_listen_ts) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: messages = parsed_message["messages"] if not messages: return last_time = messages[-1]['ts'] bot.last_listen_ts = last_time command_start = '<@'+bot.user_id.lower()+'>' for message in messages: text = message['text'].lower() if text.startswith(command_start): if 'challenge' in text: initiateThrowdown(bot, all_employees, message) break exercise = findExerciseInText(bot, text) if exercise != False: requests.post(bot.post_message_URL + "&text=" + exercise['tutorial']) break # Check for help command if 'help' in text: help_message = 'Just send me a name of an exercise, and I will teach you how to do it.' for exercise in bot.exercises: help_message += '\n ' + exercise['name'] help_message += '\n If you want to issue a challenge say `@hudl_workout I challenge @PERSON to 15 EXERCISE`' requests.post(bot.post_message_URL + "&text=" + help_message) break else: prompt_actual_command = "I'm sorry, I can't understand you" requests.post(bot.post_message_URL + "&text=" + prompt_actual_command)
download = False if not download: Log.add('图片尺寸不符,跳过') continue if download: # 获取文件名 # 此处不进行URL解码,因为有些文件名神TM带*之类的 file_name = info[1].split('/')[-1] # 文件是否已存在? if Function.exists(file_name): Log.add(info[0] + ' 已存在,跳过') continue Log.add(str(i)+' - ' + info[0] + ' 开始下载……') ts = time.time() img = Http.get(info[1], {'Host': 'files.yande.re', 'Referer': 'https://yande.re/post/show/'+info[0]}) Log.add('下载完毕。耗时:'+str(int(time.time() - ts))+'s') Function.write(file_name, img) if end: break else: break page += 1 Log.add('爬取结束') Function.write('log_' + str(int(time.time())) + '.txt', Log.get()) exit(200)
def assignExercise(bot, exercise, all_employees): # Select number of reps exercise_reps = random.randrange(exercise["minReps"], exercise["maxReps"]+1) winner_announcement = str(exercise_reps) + " " + str(exercise["units"]) + " " + exercise["name"] + " RIGHT NOW " active_users = fetchActiveUsers(bot, all_employees) winners = [] # EVERYBODY num_active_users = len(active_users) if num_active_users < 3: num_people_to_callout = 0 elif num_active_users < 6: num_people_to_callout = 1 elif num_active_users < 10: num_people_to_callout = 2 elif num_active_users < 20: num_people_to_callout = 3 else: num_people_to_callout = 5 print "num active users: " + str(num_active_users) + ", choosing " + str(num_people_to_callout) + " people" if num_people_to_callout > 0: if random.random() < bot.group_callout_chance: winner_announcement += "@channel!" # only add active users to the exercise list. This will mean if someone is active later and marks :yes: they won't get credit. for user in active_users: user.addExercise(exercise, exercise_reps) winners.append(user) else: for i in range(num_people_to_callout): winners.append(selectUser(bot, exercise, all_employees, winners, active_users)) for i in range(num_people_to_callout): winner_announcement += str(winners[i].getUserHandle()) if i == num_people_to_callout - 2: winner_announcement += ", and " elif i == num_people_to_callout - 1: winner_announcement += "!" else: winner_announcement += ", " winners[i].addExercise(exercise, exercise_reps) last_message_timestamp = str(datetime.datetime.now()) # Announce the user if not bot.debug: response = requests.post(bot.post_message_URL + "&text=" + winner_announcement) print "assignExercise response: " + response.text parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: last_message_timestamp = parsed_message["ts"] requests.post("https://slack.com/api/reactions.add?token=" + USER_TOKEN_STRING + "&name=yes&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=no&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=sleeping&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") exercise_obj = Exercises(exercise, exercise_reps, winners, last_message_timestamp) EXERCISES_FOR_DAY.append(exercise_obj) logExercise(bot,winners,exercise["name"],exercise_reps,exercise["units"],exercise_obj.time_assigned) print winner_announcement else: are_you_scared = "Not enough of you maggots are active! What are you all scared? GET BACK IN HERE!" requests.post(bot.post_message_URL + "&text=" + are_you_scared)