2012-11-24 3 views
0

не уверен, имеет ли смысл смысл, но существует ли простой способ одновременного запуска 2-х строк? (Котировки, используемые, поскольку я не уверен, как это сделать)Python запускает сразу два кода

В любом случае, что я пытаюсь сделать прямо сейчас, это сделать Skype-бот с помощью Skype4Py. Я создаю скрипт, который делает вещи, как предлагает нижеприведенный сценарий. Но я столкнулся с проблемой. Одна часть скрипта обнаруживает спам команды, но я хочу сделать какой-то таймер, который через некоторое время удалит пользователя из своей базы данных проверки спама. (Это имело смысл?). Другими словами, допустим, что спам-термация составляет спам 6 раз. После того, как пользователь вводит команду (например.! Help), возможно, 5 раз и останавливается, скажем, 3 минуты, и делает это снова 5 раз, ему не будет запрещено использовать команды.

В данный момент с этим кодом, если пользователь в любое время (например, 3 команды в 4:00 вечера, 2 команды в 16:03), пользователь будет заблокирован, но я не хочу, чтобы это работало что.

#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 = 'aw9292929296983244' 
adflyKey = '9ff83be3e71ba67e48718f90434653a6' 
adflyUID = '1185670' 
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 + 'BearNet 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 using the BearNet Bot.'); 
        elif option == 2: 
         send(nick + " hosted By ASUS-VM @ BearNet!"); 
        elif option == 3: 
         send('Want more features for the BearNet Bot? Email Andrew Wong @ [email protected]'); 
        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! For an appeal, please contact Andrew Wong @ aw9292929296983244 (Skype)'); 
           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 + 'BearNet Bot Locked!'); 

#    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 = 'BearNet' 
    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 

Но я не знаю, куда поместить его, или как

Любые виды помощи будут оценены. Спасибо!

EDIT: Изменены последнюю строку:

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

ответ

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!") 

Ребенок и родитель должен бежать в то же время, как они теперь два разных процесса.

+0

Я не понимаю, что –

+0

Как примечание стороны, Windows не имеет 'fork'. – mgilson

+0

@mgilson, есть ли другой способ? –

1

Когда вы проверяете, следует ли запрещать пользователя, вы можете проверить время последнего сообщения и сбросить счет, если оно прошло определенное время. Вы будете знать лучше, чем я, как это сделать в вашем коде. Вы не должны нуждаться в любом виде параллелизма, чтобы делать то, что вы хотите.

Смежные вопросы