0

not sure if the title makes sense, but is there a simple way for 2 'lines' to be run simultaneously? (Quotation marks used as I'm not sure how to put it)

Anyway, what I am trying to do right now is make a Skype bot with Skype4Py. I am making a script that does stuff, as the below script suggests. But I am faced with a problem. One part of the script detects command spamming, but I want to make some type of timer that would remove the user from its spam check database after a while. (Did that make sense?). In other words, let's say that the spam tolerance is spamming 6 times. After a user enters a command (eg. !help) maybe 5 times, and stops, for let's say 3 minutes, and does it again 5 times, he won't be banned from using commands.

Currently with this code, if a user, at any time (eg. 3 commands at 4:00pm, 2 command at 4:03pm), the user would be banned, but I don't want that to work like that.

#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('');

I was going to put some sort of code like this: (with time already imported)

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

But I don't know where to place it, or how

Any type of help will be appreciated. Thanks!

EDIT: Changed last line to:

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('');
Andrew Wong
  • 115
  • 10

2 Answers2

1

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

os.fork might be of use

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

The child and parent should run at the same time as they are now 2 different processes.

mgilson
  • 300,191
  • 65
  • 633
  • 696
Cruncher
  • 7,641
  • 1
  • 31
  • 65
1

When you are checking whether you should ban the user, you can check the time of the last post and reset the count if it is past a certain time. You will know better then I how to do this in your code. You shouldn't need any kind of concurrency to do what you want.

parker.sikand
  • 1,371
  • 2
  • 15
  • 32