Twitter bot not to interact with certain phrases - python

I'm making a Twitter bot that replies or likes tweets. I want it not to interact with certain phrases. For example: don't interact with tweets that have the phrase ''yellow banana". Here's my code and my attempted solution isn't working. I'm trying to get the tweet text and compare it to the "frases_naocurtir" variable that has phrase that there shouldn't be interaction. It keeps picking up these tweets and interacting.
rc = random.choice(frases)
for tweet in tweepy.Cursor(api.search_tweets, rc).items(1):
time.sleep(random.randint(time_init, time_final))
try:
cstatus = api.get_status(tweet.id, tweet_mode="extended")
text = cstatus.full_text
time.sleep(random.randint(time_init, time_final))
if rc in frases_curtir and text not in frases_naocurtir and vaicurtir != 0:
print('\nFrase buscada curtir: ' + str(rc))
tweet.favorite()
print('\nTweet curtido de: ' + tweet.user.screen_name + '\nTweet ID: ' + str(tweet.id) +
'\nTweet date: ' + str(tweet.created_at.strftime('%d/%m/%Y')))
time.sleep(random.randint(time_init, time_final))
if vairesponder != 0 and vaicurtir == 0:
rc = random.choice(frases_responder)
continue
if vairesponder == 0 and vaicurtir != 0:
rc = random.choice(frases_curtir)
continue
if vairesponder != 0 and vaicurtir != 0:
rc = random.choice(frases)
continue

Related

Using a python web crawler to scrape twitter accounts

I'm writing this program for my A-Level Computer Science coursework, and I am trying to get a crawler to scrape all the found users from a given users following/followed list.
The start of the script is as followed:
import requests
# import database as db
from bs4 import BeautifulSoup
debug = True
def getStartNode(): # Get the Twitter profile of the starting node
global startNodeFollowing # Declare the nodes vars as global for use in external functions
global startNodeFollowers
global startNodeLink
if not debug: # If debugging == False, allow the user to enter any starting node Twitter profile
startNodeLink = input("Enter a link to the starting users Twitter profile\n[URL]: ")[:-1] # Get profile link, remove the last char from input (space char, needed to enter link in terminal)
else: # If debugging == True, have predetermined starting node to save time during development
startNodeLink = ("https://twitter.com/ckjellberg03")
startNodeFollowers = (startNodeLink + "/followers") # Create a new var using the starting node's Twitter profile, append for followers and following URL pages
startNodeFollowing = (startNodeLink + "/following")
And the crawler is here:
def spider(): # Web Crawler
getStartNode()
print("\nUsing:", startNodeLink)
urlFollowers = startNodeFollowers
sourceCode = requests.get(urlFollowers)
plainText = sourceCode.text # Source code of the URL (urlFollowers) in plain text format
soup = BeautifulSoup(plainText,'lxml') # BeautifulSoup object to search through plainText for specific items/classes etc
for link in soup.findAll('a', {'class': 'css-4rbku5 css-18t94o4 css-1dbjc4n r-1loqt21 r-1wbh5a2 r-dnmrzs r-1ny4l3l'}): # 'a' is a link in HTML (anchor), class is the Twitter class for a profile
href = link.get(href)
print(href) # Display everything found (development purposes)
I'm pretty sure the class identifier for a users link to their Twitter profile from a /followers is "css-4rbku5 css-18t94o4 css-1dbjc4n r-1loqt21 r-1wbh5a2 r-dnmrzs r-1ny4l3l" from looking at source code, but printing results displays nothing.
Any advice to point me in the right direction?
Thanks!
It's pretty difficult to scrape Twitter (trust me I have try every way), you can use Twitter API but they have limitation (you can't have the name of the followers only the number) if you want to scrape some information with Twitter API you can use this code:
from TwitterAPI import TwitterAPI, TwitterPager
import tweepy
from tweepy import Cursor
from datetime import datetime, date, time, timedelta
consumer_key = 'consumer key'
consumer_secret = 'consumer secret'
token = 'token'
token_secret = 'token secret'
auth= tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(token, token_secret)
api = tweepy.API(auth)
account_list = ['POTUS44']
for target in account_list:
print("Getting data for " + target)
item = api.get_user(target)
print("name: " + item.name)
print("screen_name: " + item.screen_name)
print("description: " + item.description)
print("statuses_count: " + str(item.statuses_count))
print("friends_count: " + str(item.friends_count))
print("followers_count: " + str(item.followers_count))
tweets = item.statuses_count
account_created_date = item.created_at
delta = datetime.utcnow() - account_created_date
account_age_days = delta.days
print("Account age (in days): " + str(account_age_days))
if account_age_days > 0:
print("Average tweets per day: " + "%.2f"%(float(tweets)/float(account_age_days)))
tweets = item.statuses_count
account_created_date = item.created_at
delta = datetime.utcnow() - account_created_date
account_age_days = delta.days
print("Account age (in days): " + str(account_age_days))
if account_age_days > 0:
print("Average tweets per day: " + "%.2f"%(float(tweets)/float(account_age_days)))
hashtags = []
mentions = []
tweet_count = 0
end_date = datetime.utcnow() - timedelta(days=30)
for status in Cursor(api.user_timeline, id=target).items():
tweet_count += 1
if hasattr(status, "entities"):
entities = status.entities
if "hashtags" in entities:
for ent in entities["hashtags"]:
if ent is not None:
if "text" in ent:
hashtag = ent["text"]
if hashtag is not None:
hashtags.append(hashtag)
if "user_mentions" in entities:
for ent in entities["user_mentions"]:
if ent is not None:
if "screen_name" in ent:
name = ent["screen_name"]
if name is not None:
mentions.append(name)
if status.created_at < end_date:
break
Here is how to do it without API. Some difficulties stem from using the right
browser in User-Agent,
import re, requests
headers = { 'User-Agent': 'UCWEB/2.0 (compatible; Googlebot/2.1; +google.com/bot.html)'}
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
content = ""
for user in ['billgates']:
content += "============================\n\n"
content += user + "\n\n"
content += "============================\n\n"
url_twitter = 'https://twitter.com/%s' % user
resp = requests.get(url_twitter, headers=headers) # Send request
res = re.findall(r'<p class="TweetTextSize.*?tweet-text.*?>(.*?)</p>',resp.text)
for x in res:
x = cleanhtml(x)
x = x.replace("'","'")
x = x.replace('"','"')
x = x.replace(" "," ")
content += x
content += "\n\n"
content += "---"
content += "\n\n"

Name error on last line (it says p not defined)

Here is the code
#
# start.py
# #author Merubokkusu
# #created Fri Jan 04 2019 00:58:07 GMT-0500 (Eastern Standard Time)
# #copyright 2018 - 2019
# #license CC BY-NC-ND 3.0 US | https://creativecommons.org/licenses/by-nc-nd/3.0/us/
# #website https://github.com/Merubokkusu/discord-spam-bots/
# #email liam#merubokkusu.com
# #last-modified Tue Mar 05 2019 02:11:47 GMT-0500 (Eastern Standard Time)
#
import sys
import subprocess
import os
from time import sleep
from config import *
proxy_number = 0
spam_text = None
if os.path.exists('tokens.txt'):
userToken = open("tokens.txt").read().splitlines()
w1 = "EDIT YOUR CONFIG.PY BEFORE USING!\n-=Using tokens.txt=-\n"
else:
w1 = "EDIT YOUR CONFIG.PY BEFORE USING!\n"
if os.path.exists('proxies.txt'):
proxy_list = open("proxies.txt").read().splitlines()
else:
proxy_list = []
for token in userToken:
proxy_list.append('localhost')
if os.path.exists('combolist.txt'):
emailList = open("combolist.txt").read().splitlines()
if os.path.exists('token_gen.txt'):
tokenV = open("token_gen.txt").read().splitlines()
if len(sys.argv) < 2:
for char in w1:
sleep(0.01)
sys.stdout.write(char)
sys.stdout.flush()
sleep(0.5)
print("Type one of the following numbers to launch that spammmer")
print(" +========-Server Spammers-=========+")
print("1 : Text Spammer - Write your own text to spam")
print("2 : Image Spammer - Spam random images in a selected folder")
print("3 : Insult Spammer - Picks insults online and spams them")
print(" +========-DM Spammers-=========+ ")
print("4 : Text Spammer - Write your own text to spam")
print("5 : Image Spammer - Spam random images in a selected folder")
print("6 : Insult Spammer - Picks insults online and spams them")
print(" +========-Other-=========+")
print("7 : Join Server - Join the server thats written in the config")
print(" +========-Account Creator-=========+")
print("8 : Account creator - Create bulk accounts")
print("9 : Account verifier - Verify accounts")
in_pick = float(input("Select a bot: "))
else:
in_pick = float(sys.argv[1])
spam_text = sys.argv[2]
if in_pick == 1:
if os.path.exists('text.txt'):
for token in userToken:
p = subprocess.Popen([pythonCommand,'bots/server/discord_text_spam.py',token,'null',proxy_list[proxy_number]])
proxy_number += 1
sleep(1)
else:
if spam_text == None:
spam_text = input("Write spam text : ")
for token in userToken:
p = subprocess.Popen([pythonCommand,'bots/server/discord_text_spam.py',token,spam_text,proxy_list[proxy_number]])
proxy_number += 1
sleep(1)
if in_pick == 2:
for token in userToken:
p = subprocess.Popen([pythonCommand, 'bots/server/discord_image_spam.py', token,proxy_list[proxy_number]])
proxy_number += 1
if in_pick == 3:
for token in userToken:
p = subprocess.Popen([pythonCommand,'bots/server/discord_insult_spam.py', token,proxy_list[proxy_number]])
proxy_number += 1
#DM Spammers
if in_pick == 4:
if os.path.exists('text.txt'):
if not os.path.exists('dm_spam_text.txt'):
file = open('dm_spam_text.txt','w')
file.write('=====Merubokkusu=====\n')#This is written for bug issues :/
file.close()
for token in userToken:
p = subprocess.Popen([pythonCommand,'bots/DM/discord_text_spam_dm.py',token,'null',proxy_list[proxy_number]])
proxy_number += 1
sleep(2.5)
else:
if not os.path.exists('dm_spam_text.txt'):
file = open('dm_spam_text.txt','w')
file.write('=====Merubokkusu=====\n')#This is written for bug issues :/
file.close()
if spam_text == None:
spam_text = input("Write spam text : ")
for token in userToken:
p = subprocess.Popen([pythonCommand,'bots/DM/discord_text_spam_dm.py',token,spam_text,proxy_list[proxy_number]])
proxy_number += 1
sleep(2.5)
if in_pick == 5:
if not os.path.exists('dm_spam_image.txt'):
file = open('dm_spam_image.txt','w')
file.write('=====Merubokkusu=====\n')#This is written for bug issues :/
file.close()
for token in userToken:
p = subprocess.Popen([pythonCommand, 'bots/DM/discord_image_spam_dm.py', token,proxy_list[proxy_number]])
proxy_number += 1
if in_pick == 6:
if not os.path.exists('dm_spam_insult.txt'):
file = open('dm_spam_insult.txt','w')
file.write('=====Merubokkusu=====\n')#This is written for bug issues :/
file.close()
for token in userToken:
p = subprocess.Popen([pythonCommand,'bots/DM/discord_insult_spam_dm.py', token,proxy_list[proxy_number]])
proxy_number += 1
if in_pick == 7:
for token in userToken:
if userToken == False:
enp = token.split(':')
p = subprocess.Popen([pythonCommand,'bots/misc/joinServer.py',enp[0],enp[1],inviteLink,useBrowser,proxy_list[proxy_number]])
proxy_number += 1
sleep(joinSpeed)
else:
p = subprocess.Popen([pythonCommand,'bots/misc/joinServer2.0.py',token,inviteLink,proxy_list[proxy_number]])
proxy_number += 1
sleep(joinSpeed)
if in_pick == 8:
if(captchaAPI == ""):
print("This requires an API key from https://2captch9a.com/")
else:
for combo in emailList:
enp = combo.split(':')
p = subprocess.Popen([pythonCommand,'bots/misc/account-creator/account_creator.py',enp[0],enp[1],proxy_list[proxy_number]])
proxy_number += 1
sleep(joinSpeed)
if in_pick == 9:
if(captchaAPI == ""):
print("This requires an API key from https://2captcha.com/")
else:
for combo in emailList:
for tknv in tokenV:
enp = combo.split(':')
p = subprocess.Popen([pythonCommand,'bots/misc/account-creator/account_verify.py',enp[0],enp[1],proxy_list[proxy_number],tknv])
proxy_number += 1
sleep(joinSpeed)
p.wait()
It just says name error for p.wait that p isn't defined (im a noob)
I tried everything and it still will not work! I need this for a bot I am developing and I am trying to do this but I have only this issue so help me out :) (BTW I only get the error when I select 8 or 9)
It could be because no one of those if statement is satisfied and so p won't be created(Since p is only defined inside of the many if statement). You should define it in the beginnig of the file and the let, if one of those if statement get triggered, be modified.

How do I get this while loop and json response to work?

The first time the script is run with input userid and if the user is online, it runs fine until the print(f'{username}, {userid}' + ' is still online...') gets stuck.
The program never continues to the else: when the user go offline and while userid == str(ps['user_id']): is no longer True.
It's like the str(ps['user_id']): never updates in the script when called.
userid = input('Input userID: ')
response = requests.post('website.com/api', headers=headers, data=data)
json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)
while True: # Main loop to run if a user is online
for ps in data['result']['page']['list']:
if userid == str(ps['user_id']): # If a user is online print details
username = ps['nick_name']
print('Username: ' + ps['nick_name'])
print('UserID: ' + str(ps['user_id']))
while userid == str(ps['user_id']): # Look if the user is still online (is in the json response)
print(f'{username}, {userid}' + ' is still online...')
time.sleep(3)
else: # If user go offline(is not in the json response), break and restart main loop(first while loop).
break
print('Waiting for ' + f'{userid}' + ' to get online...') # Message until user go online again (is found in the json response).
time.sleep(5)
You are not updating data anywhere inside of your loop so its using the same stale data for every iteration. You can just add your three lines to generate data into your loop before the time.sleep(5). This will give you updated data and should resolve your issue.
userid = input('Input userID: ')
response = requests.post('website.com/api', headers=headers, data=data)
json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)
userList = data['result']['page']['list']
isOnline = 0
while True: # Main loop to run if a user is online
hasLoggedIn = 0
for user in userList:
if str(user['user_id']) == userid and isOnline == 0: # If a user is online print details
username = user['nick_name']
print('Username: ' + user['nick_name'])
print('UserID: ' + str(user['user_id']))
print(f'{username}, {userid}' + ' is now online...')
isOnline = 1
hasLoggedIn = 1
time.sleep(3)
elif str(user['user_id']) == userid and isOnline == 1:
print(f'{username}, {userid}' + ' is still online...')
hasLoggedIn = 1
time.sleep(3)
if hasLoggedIn == 0:
print('Waiting for ' + f'{userid}' + ' to get online...') # Message until user go online again (is found in the json response).
isOnline = 0
time.sleep(5)
response = requests.post('website.com/api', headers=headers, data=data)
json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)
userList = data['result']['page']['list']

Variable being sent as blank in message

I'm trying to write a previous messages bot for (he)xchat. Saving and printing the messages is fine, but when it sends it doesn't retain the message.
I've tried all sorts of methods to fix it but it's always blank.
Problem area:
for y in range(0, 14):
if msg_last[y]:
msg_to_say = 'privmsg ' + triggernick + ' <previously_bot> '
msg_to_say = msg_to_say + msg_last[y]
print (msg_to_say)
destination.command(msg_to_say)
Inside of Xchat it'll print:
privmsg <nick> <previously_bot> $msg
but upon sending it it'll be:
privmsg <nick> <previously_bot>
Can anyone spot what I've missed?
Full code:
from random import randint
import xchat
__module_name__ = "Blake's Previous Messages Bot"
__module_version__ = " v0.1 "
__module_description__ = "A previous message bot"
print("\0034", __module_name__, __module_version__, __module_description__, "!\003")
#---Globals---#000000#FFFFFF----------------------------------------------------
msg_last = [str()] * 15
msg_count = 0
def on_chat(word, word_eol, userdata):
global msg_count
global msg_last
msg = word[1]
if msg_count == 15:
#print ("Full, reloading list")
for x in range(0, 14):
msg_last[x + 1] = msg_last[x]
msg_last[0] = msg
msg_count = 0
msg_last[msg_count] = msg
msg_count = msg_count + 1
def on_join(word, word_eol, userdata):
global msg_last
triggernick, triggerchannel, triggerhost = word
destination = xchat.get_context()
print ("Someone joined, pulling up log")
for y in range(0, 14):
if msg_last[y]:
msg_to_say = 'privmsg ' + triggernick + ' <previously_bot> '
msg_to_say = msg_to_say + msg_last[y]
print (msg_to_say)
destination.command(msg_to_say)
return xchat.EAT_ALL
def on_kevin(word, word_eol, userdata):
triggernick, triggerchannel, triggerhost = word
destination = xchat.get_context()
if triggernick == 'TenEighths':
rnd = randint(0,2)
if rnd == 2:
rnd2 = randint(0,3)
rnd_str = heyYouKevin()
destination.command("say " + rnd_str)
#print ("Someone joined, pulling up log")
def heyYouKevin(x):
return {
'0': 'be quiet Kevin',
'1': 'omg TenEighths, will you be quiet already?',
'2': 'Kevin is spouting nonsense',
'3': "be quiet, TenEighths.",
}[x]
xchat.hook_print('Join', on_join)
xchat.hook_print('Channel Message', on_chat)
xchat.hook_print('Channel Message', on_kevin)
If you use the raw irc command PRIVMSG the syntax requires that any strings with spaces start with :. So PRIVMSG nick :This is a long string. The better solution is to just use xchat.command('msg nick ...') since it knows what to do.

Python Run Two Codes At Once

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

Categories