0

不确定标题是否有意义,但是是否有一种简单的方法可以同时运行 2 条“行”?(因为不知道怎么写,所以用引号)

无论如何,我现在要做的是用 Skype4Py 制作一个 Skype 机器人。正如下面的脚本所暗示的,我正在制作一个可以做事的脚本。但我面临一个问题。脚本的一部分检测命令垃圾邮件,但我想制作某种类型的计时器,一段时间后将用户从其垃圾邮件检查数据库中删除。(这有意义吗?)。换句话说,假设垃圾邮件容忍度是垃圾邮件 6 次。在用户输入命令(例如!帮助)可能 5 次后,停止,比如说 3 分钟,再执行 5 次,他不会被禁止使用命令。

目前使用此代码,如果用户在任何时间(例如下午 4:00 执行 3 个命令,下午 4:03 执行 2 个命令),该用户将被禁止,但我不希望那样工作。

#IMPORTS
import hashlib
import os
import random
import re
import string
import sys
sys.path.append('lib')
import time
import urllib
import Skype4Py
import urllib2


#CONFIG
admin = '...'
adflyKey = '...'
adflyUID = '...'
nick = ''

#SETUP
accessList = []
bannedList = []
safeuserList = []
vwordList = []
bcheck = []
quoteList = []
commandList = []
lock = False
msgcount = 1

#ADF.LY GENERATOR
def adfLY(url):
    global adflyKey
    global adflyUID
    try:
        location = 'http://api.adf.ly/api.php?key=' + adflyKey + '&uid=' + adflyUID + '&advert_type=int&domain=adf.ly&url=' + url
        link = urllib.urlopen(location).read()
        return link
    except:
        return url
#RANDOM STRING
def getRandom(length):
    length = int(length)
    charSet = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
    randomChar = ''.join(random.sample(charSet,length))
    return randomChar

#GET URL TITLE
def getTitle(url, maxRead = 10000):
    try:
        url = url.lower()
        url = url.replace('cmyip', 'google', 1);
        website = urllib2.urlopen(url)
        title = re.compile('<title>(.+?)</title>')
        buffer = ''
        while True:
            data = website.read(100)
            if not data:
                return 'Unknown'
            buffer += data
            match = title.search(buffer)
            if match:
                return ' '.join(line.strip() for line in match.group(1).strip().split('\n'))
            elif len(buffer) >= maxRead:
                return 'Unknown'
    except:
        return 'Unknown'

#IS URL UP
def isUP(url):
    try:
        results = getTitle('http://downforeveryoneorjustme.com/' + url)
        results = results.replace('Is Up -> Check if your website is up or down?', ' is UP.', 1);
        results = results.replace('Is Down -> Check if your website is up or down?', ' is DOWN.', 1);
        results = results.replace(' -> Huh? Error... - Check if your website is up or down?', ' is INVALID.', 1);
        return results
    except:
        return url + ' is UNKNOWN.'

#MD5 HASH
def md5(word):
    md5 = hashlib.md5(word)
    return md5.hexdigest()

#UPDATE ACCESS/BANNED LIST
def updateList(list):
    global accessList
    global bannedList
    global vwordList
    global commandList
    if list == 'access':
        accessFile = open('database/access.txt', 'w')
        for name in accessList:
            accessFile.write(name + '\n')
        accessList.sort()
        accessFile.close
    elif list == 'banned':
        bannedFile = open('database/banned.txt', 'w')
        for name in bannedList:
            bannedFile.write(name + '\n')
        bannedList.sort()
        bannedFile.close
    elif list == 'vword':
        vwordFile = open('database/vword.txt', 'w')
        for word in vwordList:
            vwordFile.write(word + '\n')
        vwordList.sort()
        vwordFile.close
    elif list == 'safeuser':
        safeuserFile = open('database/safeuser.txt', 'w')
        for word in safeuserFile:
            safeuserFile.write(word + '\n')
        safeuserFile.sort()
        safeuserFile.close
#SKYPE4PY API
def OnAttach(status):
    if status == Skype4Py.apiAttachAvailable:
        skype.Attach()
        return
    if status == Skype4Py.apiAttachSuccess:
        print('API connected to the Skype process!')
        print '------------------------------------------------------------------------------'
        return
    statusAPI = skype.Convert.AttachmentStatusToText(status)
    print 'API '+ statusAPI.lower() + '...'

#deny calls
#AllowedCallTargets = set (['echo123', 'echo223']);
#
#class receive_set:
#    def __init__(self):
#        pass
#    def OnCall(self, call, status):
#        print "status is ", status, " Peer is: ", call.PartnerHandle, " Show name is ", call.PartnerDisplayName
#        print "length of active calls are ",len(self.skype.ActiveCalls)
#        inprogress = False
#        if (status == Skype4Py.clsRinging) and (call.Type == Skype4Py.cltIncomingP2P or call.Type == Skype4Py.cltIncomingPSTN):
#            for curr in self.skype.ActiveCalls:
#                print "Call status is ", curr.Type, " status is ", curr.Status
#                if curr.Status == Skype4Py.clsInProgress :
#                    inprogress = True
#            if not inprogress:
#                call.Answer()
#        if (status == Skype4Py.clsInProgress):
#            print "Call's video send status is ",call.VideoSendStatus, " Recv status is ", call.VideoReceiveStatus, " Video Status is ",call.VideoStatus
##            cmd  = self.skype.Command("ALTER CALL <id> START_VIDEO_SEND")
##            self.skype.SendCommand(cmd)
#
##        if (status == "ROUTING") and (not call.PartnerHandle in AllowedCallTargets):
#            call.Finish()
#            print 'Terminating call'
#
#    def OnCallVideoReceiveStatusChanged(self, status):
#        pass
#
#    def OnCallVideoSendStatusChanged(self, status):
#        pass
#
#    def OnCallVideoStatusChanged(self, status):
#        pass
#
#    def OnAttach(self, status):
#        print 'API attachment status:'+self.skype.Convert.AttachmentStatusToText(status)
#        if status == Skype4Py.apiAttachAvailable:
#            self.skype.Attach()
#            
#    def start(self):
#        self.skype = Skype4Py.Skype()
#        self.skype.OnAttachmentStatus = self.OnAttach
#        self.skype.OnCallStatus = self.OnCall
#
#
#    def Attach(self):
#        self.skype.Attach()
#
#    def Callout(self, callee):
#        self.skype.PlaceCall(callee)
#
#
#if __name__ == "__main__":
#    rec = receive_set()
#    rec.start()
#    rec.Attach()
#
#    while 1:
#        time.sleep(1)



#COMMANDS
def OnMessageStatus(Message, Status):
    global admin
    global nick
    global lock
    global accessList
    global bannedList
    global safewordList
    global commandList
    global bcheck
    global vwordList
    global quoteList
    global msgcount
    try:
        msg = Message.Body
        chat = Message.Chat
        send = chat.SendMessage
        senderDisplay = Message.FromDisplayName
        senderHandle = Message.FromHandle
        message = ''
        if lock == True:
            if Status == 'SENT' or (Status == 'RECEIVED' and senderHandle in accessList):
                if msg == '!unlock':
                    lock = False
                    send(nick + ' Unlocked!');

        if lock == False:
            if Status == 'RECEIVED' and senderHandle not in bannedList:
                msgcount = msgcount + 1

                if msgcount == 30:
                    option = random.randint(1, 3)
                    time.sleep(3)
                    if option == 1:
                        send('Type "!info" or "!help" for common information and help.');
                    elif option == 2:
                        send(nick);
                    elif option == 3:
                        send('');
                    msgcount = 1

                messageTemp = msg.split()
                n = 0
                did_it_work = False
                if msg.startswith('!'):
                    for x in commandList:
                        if messageTemp[0] == x:
                            did_it_work = True
                    if did_it_work == True:
                        print('[NOTICE] '+ senderDisplay +' ('+senderHandle+') issued command: '+"'"+msg+"'")
                        if senderHandle not in safeuserList:
                            for x in bcheck:
                                if x == senderHandle:
                                    n += 1
                            if n == 9: #<--- ###Trigger word is 1 above the number### aka the 10th command is the trigger.
                                send(nick + senderDisplay + ', you are now banned from using commands due to flooding!');
                                bannedList.append(senderHandle)
                                updateList('banned')
                                while n < 0:
                                    bcheck.remove(senderHandle)
                                    n -= 1
                            else:
                                bcheck.append(senderHandle)
                                n = 0
            else:
                n = 0

                if msg.lower().startswith(admin):
                    print '\a'

            if Status == 'SENT' or (Status == 'RECEIVED' and senderHandle not in bannedList):

###           #     if msg in vwordList :
###              #      send.can;
###                 #   print 'A'

                if msg == '!help':
                    helpFile = open('help.txt','r')
                    for line in helpFile.readlines():
                        message = message + nick + line
                    send(message);

                if msg == '!info':
                    infoFile = open('info.txt','r')
                    for line in infoFile.readlines():
                        message = message + nick + line
                    send(message);

                if msg.startswith('!isup '):
                    url = msg.replace('!isup ', '', 1);
                    send(nick + isUP(url));

                if msg.startswith('!md5 '):
                    word = msg.replace('!md5 ', '', 1);
                    send(nick + 'MD5 Hash : ' + md5(word));

                if msg.startswith('!os '):
                    if senderHandle in safeuserList:
                        command = msg.replace('!os ', '', 1);
                        os.system(command);

                if msg.startswith('!topic '):
                    topic = msg.replace('!topic ', '', 1);
                   # Message.Body = 'Changing topic name to...'
                    send("[NOTICE] Changing topic by user's request");
                    send('/topic ' + topic);

            if Status == 'SENT' or (Status == 'RECEIVED' and senderHandle in accessList):
                if msg.startswith('!access '):
                    if msg.startswith('!access add '):
                        name = msg.replace('!access add ', '', 1);
                        if name in accessList:
                            send(nick + 'User [' + name + '] already has access!');
                        elif name not in accessList:
                            accessList.append(nick)
                            accessList.sort()
                            updateList('access')
                            send(nick + 'User [' + name + '] has gained access!');
                    elif msg.startswith('!access list'):
                        name = msg.replace('!access list ', '', 1);
                        for name in accessList:
                            message = message + nick + name + '\n'
                        send(message);
                    elif msg.startswith('!access remove '):
                        name = msg.replace('!access remove ', '', 1);
                        if name in accessList:
                            accessList.remove(name)
                            accessList.sort()
                            updateList('access')
                            send(nick + 'User [' + name + '] has lost access!');
                    elif nick not in accessList:
                        send(nick + 'User [' + name + '] has no access!');

                if msg.startswith('!vword '):
                    if msg.startswith('!vword add '):
                        name = msg.replace('!vword add ', '', 1);
                        if name in vwordList:
                            send('Word Already Stored!');
                        elif name not in vwordList:
                            vwordList.append(nick)
                            vwordList.sort()
                            updateList('vword')
                            send('Word Stored');
                    elif msg.startswith('!vword list'):
                        name = msg.replace('!vword list ', '', 1);
                        send('Please refer to the vword.txt');

                if msg.startswith('!ban '):
                    if msg.startswith('!ban add '):
                        name = msg.replace('!ban add ', '', 1);
                        if name in bannedList:
                            send(nick + 'User [' + name + '] is already banned!');
                        elif name not in bannedList:
                            bannedList.append(nick)
                            bannedList.sort()
                            updateList('banned')
                            send(nick + 'User [' + name + '] has been banned!');
                    elif msg.startswith('!ban list'):
                        name = msg.replace('!ban list ', '', 1);
                        for name in bannedList:
                            message = message + nick + name + '\n'
                        send(message);
                    elif msg.startswith('!ban remove '):
                        name = msg.replace('!ban remove ', '', 1);
                        if name in bannedList:
                            bannedList.remove(name)
                            bannedList.sort()
                            updateList('banned')
                            send(nick + 'User [' + name + '] has been unbanned!');
                        elif nick not in bannedList:
                            send(nick + 'User [' + name + '] is not banned!');

          #      if msg.contains('youtube.com/watch?v='):
             #       for friend in skype.Friends:
                #        if not friend.OnlineStatus == Skype4Py.olsOffline:
                   #         try:
                      #          skype.CreateChatWith(friend.Handle).SendMessage(nick + '[GLOBAL MESSAGE]\r\n' + nick + message)
                         #   except:
                            #    print '[ERROR] ' + str(sys.exc_info()[1])

                if msg.startswith('!global '):
                    message = msg.replace('!global ', '', 1);
                    for friend in skype.Friends:
                        if not friend.OnlineStatus == Skype4Py.olsOffline:
                            try:
                                skype.CreateChatWith(friend.Handle).SendMessage(nick + '[GLOBAL MESSAGE]\r\n' + nick + message)
                            except:
                                print '[ERROR] ' + str(sys.exc_info()[1])
                if msg == '!lock':
                    lock = True
                    send(nick);

#                if msg == '!party':
#                    send('/topic PARTY HARD!');
#                    for friend in skype.Friends:
#                        if not friend.OnlineStatus == Skype4Py.olsOffline:
#                            try:
#                                send('/add ' + friend.Handle);
#                            except:
#                                print '[ERROR] ' + str(sys.exc_info()[1])

                if msg == '!restart':
                    os.system('python restart.py');
                    sys.exit();
    except:
        send(nick + '[ERROR] ' + str(sys.exc_info()[1]));

#START INSTANCE
import os
if os.name == 'nt':
    os.system('cls')
else:
    os.system('clear')
print '******************************************************************************'
infoFile = open('info.txt','r')
for line in infoFile.readlines():
    print '- ' + line.replace('\n', '')
print 'Checking for Skype4Py API...'
try:
    import Skype4Py
    skype = Skype4Py.Skype();
    skype.OnAttachmentStatus = OnAttach
    skype.OnMessageStatus = OnMessageStatus
    skype.FriendlyName = ''
    print 'Skype4Py API found!'
except:
    print 'Failed to locate Skype4Py API! Quitting...'
    print '******************************************************************************'
    sys.exit() 
print 'Checking for Skype process...'
if skype.Client.IsRunning:
    print 'Skype process found!'
elif not skype.Client.IsRunning:
    print 'Skype process not found!'
    try:
        print 'Starting Skype process...'
        skype.Client.Start()
    except:
        print 'Failed to start Skype process! Quitting...'
        print '******************************************************************************'
        sys.exit() 
print 'Connecting API to Skype...'
try:
    skype.Attach();
except:
    print 'Failed to connect API to Skype! Quitting...'
    print '******************************************************************************'
    sys.exit()
print 'Loading access list...'
accessFile = open('database/access.txt','r')
for line in accessFile.readlines():
    name = line.replace('\n', '');
    accessList.append(name)
    accessList.sort()
accessFile.close()
print 'Access list contains ' + str(len(accessList)) + ' names!'
print 'Loading banned list...'
bannedFile = open('database/banned.txt','r')
for line in bannedFile.readlines():
    name = line.replace('\n', '');
    bannedList.append(name)
    bannedList.sort()
bannedFile.close()
print 'Banned list contains ' + str(len(bannedList)) + ' names!'
print 'Loading VWORD list...'
vwordFile = open('database/vword.txt','r')
for line in vwordFile.readlines():
    name = line.replace('\n', '');
    vwordList.append(name)
    vwordList.sort()
vwordFile.close()
print 'VWORD list contains ' + str(len(vwordList)) + ' words!'
print 'Loading quote list...'
quoteFile = open('database/quote.txt','r')
for line in quoteFile.readlines():
    quote = line.replace('\n', '');
    quoteList.append(quote)
    quoteList.sort()
quoteFile.close()
print 'Quote list contains ' + str(len(quoteList)) + ' quotes!'
print 'Loading safe user list...'
safeuserFile = open('database/safeuser.txt','r')
for line in safeuserFile.readlines():
    safeuser = line.replace('\n', '');
    safeuserList.append(safeuser)
    safeuserList.sort()
safeuserFile.close()
print 'SafeUser list contains ' + str(len(safeuserList)) + ' names!'
print 'Loading command list...'
commandFile = open('database/commands.txt','r')
for line in commandFile.readlines():
    command = line.replace('\n', '');
    commandList.append(command)
    commandList.sort()
commandFile.close()
print 'Command list contains ' + str(len(commandList)) + ' commands!'
print '******************************************************************************'
#ENDLESS LOOP
while True:
    raw_input('');

我打算放一些这样的代码:(已经导入了时间)

timer=180
while timer >0:
    time.sleep(1)
    timer -=1

但我不知道放在哪里,或者如何

任何类型的帮助将不胜感激。谢谢!

编辑:将最后一行更改为:

timer=16
while timer >0:
    time.sleep(1)
    timer -=1
    if timer == 12:
        ccheck = bcheck
        ccheck.reverse()
        dcheck = len(ccheck)
        while dcheck !=0:
            for x in ccheck:
                if x == ccheck[0]:
                    bcheck.remove(x)
            ccheck = []
#raw_input('');
4

2 回答 2

1

http://docs.python.org/2/library/os.html

os.fork可能有用

pid = os.fork()
if pid == 0:
    print("I am the child!")
else:
    print("I am the parent!")

子进程和父进程应该同时运行,因为它们现在是 2 个不同的进程。

于 2012-11-24T06:07:35.790 回答
1

当您检查是否应该禁止用户时,您可以检查最后一次发布的时间,如果超过一定时间则重置计数。您会比我更了解如何在您的代码中执行此操作。你不应该需要任何并发来做你想做的事。

于 2012-11-24T06:12:41.587 回答