我创建了一个无限循环来检查好友请求,如果有的话,它会接受它们,因此脚本会永远持续下去。
请参阅此处的代码:
while True:
snaps = s.get_snaps()
for sender in snaps:
if sender['media_type'] == 3:
s.add_friend(sender[u'sender'])
friends = s.get_friends()
names = []
for friend in friends:
if friend['type'] == 0:
names.append(friend[u'name'])
print "Amount of confirmed friends:",
print len(names),
print "/ 6000"
到目前为止,该脚本可以正常工作,但并不完全符合我想要的方式。
它一遍又一遍地打印X/6000,这就是困扰我的原因。我只希望脚本在实际接受/多个好友请求时执行"打印"部分
所以这部分:
print "Amount of confirmed friends:",
print len(names),
print "/ 6000"
只有在某人实际被接受为好友时才能打印,从而更新已确认好友的数量。
我在这里百感交集,我从来没有在使用if
陈述等方面如此详细。
我考虑过的场景是:
将 if 语句放在添加某人的地方,如果结果是(好?(,它将继续到脚本的其余部分。
或者在打印之前在底部放置一个 if 语句,说如果某人实际添加,它就会打印,否则它会回到重复自己。
这里要记住的几件事,对 snapchat 服务器的请求/活动越少越好。因此,如果我可以在脚本的开头限制它,那将是首选。
虽然我不知道该怎么做。
有人可以解释一下我如何检查是否有人(或多个人(与 media_type 3 一起找到,如果有,它会继续脚本。如果没有,它会休眠几秒钟,然后重新尝试。
我觉得这是一个微妙的话题,我担心我会搞砸我的代码,最终不知道我到底在做什么,并为此感到沮丧。在询问之前,我已经联系了Google和TutorialsPoint,但是我仍然无法应用我读过的任何内容,因为我不知道如何操作。
为了尽量减少对 snapchat 的调用次数,我会排除s.get_friends()
调用,以便它仅在脚本运行时执行此操作:
import time
total_friends = len([friend for friend in s.get_friends()
if friend['type'] == 0])
SLEEP_TIME = 60
while True:
new_friends = 0
snaps = s.get_snaps()
for sender in snaps:
if sender['media_type'] == 3:
s.add_friend(sender[u'sender'])
new_friends += 1
total_friends += new_friends
if new_friends:
print 'Amount of confirmed friends:'
print total_friends, '/ 6000'
time.sleep(60)
这将获得您在进入循环之前拥有的当前朋友数量。 然后它得到(大概是新的?(快照,添加正确media_type
的快照并同时递增new_friends
。 如果new_friends
不为 0,则打印新的好友总数。
这个解决方案会对你有所帮助。您可以跟踪第一次收到朋友的时间,以避免在第一次跑步时发送消息。然后,您只需将previous_friends与当前好友进行比较即可指示更改。
# Used to mark the initial receiving of the friends
friends_received = False
# Will store the names of all friends from the last loop
previous_friends = []
while True:
new_friend = False
snaps = s.get_snaps()
for sender in snaps:
if sender['media_type'] == 3:
s.add_friend(sender[u'sender'])
friends = s.get_friends()
names = []
for friend in friends:
if friend['type'] == 0:
names.append(friend[u'name'])
# Checking if new friends have been received
if friends_received and len(friends) > len(previous_friends):
# New friends are available
new_friend = True
if new_friend:
print "Amount of confirmed friends:",
print len(names),
print "/ 6000"
# Keeping a record of the friends from the last loop
if len(previous_friends) == 0:
friends_received = True
previous_friends = friends
这样做怎么样:
friendAdded = false
snaps = s.get_snaps()
for sender in snaps:
if sender['media_type'] == 3:
s.add_friend(sender[u'sender'])
friends = s.get_friends()
names = [];
for friend in friends:
if friend['type'] == 1:
names.append(friend[u'name'])
friendAdded = true
if friendAdded == true:
print "Amount of confirmed friends:",
print len(names),
print "/ 6000"
friendAdded = false
现在,它只会在您添加新朋友时打印。