I'm working on a simple IRC bot and I'm trying to create a timer highlight function.
When I enter the following:
!hl
10
I want to assign 10 (or whatever might be there in it's place) as a variable called 'var_time' in minutes.
var_time= 0 #External statement
def timer_commands(nick,channel,message):
global var_time
if message.find("!hl", var_time )!=-1:
ircsock.send('PRIVMSG %s :%s I will highlight you in %s minutes!\r\n' % (channel,nick, var_time))
time.sleep(float(var_time)) #The delay here is in seconds
ircsock.send('PRIVMSG %s :%s, You asked me %s minutes ago to highlight you.!\r\n' % (channel,nick,var_time))
I know var_time is not taking the value 10, that is precisely my question, how can I make that happen?
Here is how the function is called:
while 1:
ircmsg = ircsock.recv(2048) # receive data from the server
ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
ircraw = ircmsg.split(' ')
print(ircmsg) # Here we print what's coming from the server
if ircmsg.find(' PRIVMSG ')!=-1:
nick=ircmsg.split('!')[0][1:]
channel=ircmsg.split(' PRIVMSG ')[-1].split(':')[0]
timer_commands(nick,channel,ircmsg)
Thanks in advance.
Solution:
def timer_commands(nick,channel,message):
if ircraw[3] == ':!hl':
var_time = float(ircraw[4])
ircsock.send('PRIVMSG %s :I will highlight you in %s minutes!\r\n' % (channel, nick, ircraw[4]))
time.sleep(var_time*60) #Delay in Minutes
ircsock.send('PRIVMSG %s :%s pYou asked me %s minutes ago to highlight you.! \r\n' % (channel, nick, ircraw[4]))
Thanks Anonymous
try regular expressions:
>>> re.match('!hl ([0-9]+)$', '!hl 91445569').groups()[0]
'91445569'
>>> re.match('!hl ([0-9]+)$', '!hl 1').groups()[0]
'1'
or, in your code:
import re
m = re.match('!hl ([0-9]+)$', ircmsg)
if m is not None:
var_time = int(re.groups()[0])
Related
I have the Below python code which I'm using to determine the Linux bond/team status. This code works just fine. I am not good at aligning the output formatting thus getting little hiccup.
I wanted the Printing Format into a Certain format, would appreciate any help on the same.
Below is the code exercise:
#!/usr/bin/python
# Using below file to process the data
# cat /proc/net/bonding/bond0
import sys
import re
def usage():
print '''USAGE: %s [options] [bond_interface]
Options:
--help, -h This usage document
Arguments:
bond_interface The bonding interface to query, eg. 'bond0'. Default is 'bond0'.
''' % (sys.argv[0])
sys.exit(1)
# Parse arguments
try:
iface = sys.argv[1]
if iface in ('--help', '-h'):
usage()
except IndexError:
iface = 'bond0'
# Grab the inf0z from /proc
try:
bond = open('/proc/net/bonding/%s' % iface).read()
except IOError:
print "ERROR: Invalid interface %s\n" % iface
usage()
# Parse and output
active = 'NONE'
Link = 'NONE'
slaves = ''
state = 'OK'
links = ''
bond_status = ''
for line in bond.splitlines():
m = re.match('^Currently Active Slave: (.*)', line)
if m:
active = m.groups()[0]
m = re.match('^Slave Interface: (.*)', line)
if m:
s = m.groups()[0]
slaves += ', %s' % s
m = re.match('^Link Failure Count: (.*)', line)
if m:
l = m.groups()[0]
links += ', %s' % l
m = re.match('^MII Status: (.*)', line)
if m:
s = m.groups()[0]
if slaves == '':
bond_status = s
else:
slaves += ' %s' % s
if s != 'up':
state = 'FAULT'
print "%s %s (%s) %s %s %s" % (iface, state, bond_status, active, slaves, links)
Result:
$ ./bondCheck.py
bond0 OK (up) ens3f0 , ens3f0 up, ens3f1 up , 0, 0
Expected:
bond0: OK (up), Active Slave: ens3f0 , PriSlave: ens3f0(up), SecSlave: ens3f1(up) , LinkFailCountOnPriInt: 0, LinkFailCountOnSecInt: 0
I tried to format in a very basic way as shown below :
print "%s: %s (%s), Active Slave: %s, PriSlave: %s (%s), SecSlave: %s (%s), LinkFailCountOnPriInt: %s, LinkFailCountOnSecInt: %s" % (iface, state, bond_status, active, slaves.split(',')[1].split()[0], slaves.split(',')[1].split()[1], slaves.split(',')[2].split()[0], slaves.split(',')[2].split()[1], links.split(',')[1], links.split(',')[2])
RESULT:
bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LinkFailCountOnPriInt: 1, LinkFailCountOnSecInt: 1
However, I would suggest to get the values into variables prior and then use them in the print statement so as to avoid "out of index" issues during print() , as in rare cases like bond with only one interface will report indexing error while splitting hence good to get the values in variable and suppress the out of index into exception for those cases.
Do not use the way with "/proc/net/bonding/%s' for querying bond status. It could trigger system panic. Try to use "/sys/class/net/bondX/bonding", it is more safe.
I'm using a bot for twitch and it tracks the time the user has spent in the channel. !time You have spent 10 seconds in the stream. However when multiple users use this command !time it doesn't have a seperate 'count' for each user. Ex:
Rustie: !time
Bot: Rustie, you have 20 seconds in the stream.
~1 minute later~
John: !time
Bot: John, you have 1 minute 20 seconds in the stream.
My current code:
usersForTime = []
if "time" in message:
if user in usersForTime:
endTime = time.time() # I already made startTime in the !start command (which starts the time tracker in the first place)
ellapsed = (endTime - startTime)
sendMessage(s, user + ", you have " + "%.2f" % round(ellapsed, 2) + " seconds in the stream.")
else:
sendMessage(s ,"You need to start tracking your time with the !start command.")
You'll want to store startTime associated with a specific user, something like
userStart = {}
if user in usersForTime:
...
ellapsed = (endTime - userStart[user])
which uses a dictionary to look up the individual's startTime.
To store it originally (in !start):
userStart[user] = time.time()
Thanks to the great documentation online for Rally API, I know how to create test steps and update a defect/test case.
A similar question has been asked and answered regarding usage with ...
However, I did not succeed updating a test step by using python API (pyral).
I have tried the following code:
TCid = "TC1392"
testcase=rally.get('TestCase', query='FormattedID = %s' % TCid, instance=True)
print "Updating steps for Test Case %s" % testcase.FormattedID
#Test Steps
try:
for i in range(3):
input="Step Input for Step: "+str(i)
expected_result="Expected Result for Step: "+str(i)
testcasestep_fields = {
"TestCase" : testcase.ref,
"StepIndex" : i,
"Input" : input,
"ExpectedResult" : expected_result
}
testcasestep = rally.update('TestCaseStep', testcasestep_fields)
print "Steps of TestCase %s updated\n" % testcase.FormattedID
except RallyRESTAPIError, details:
sys.stderr.write('ERROR: %s \n\n' % details)
But this returns the following error: An identifying field (Object or FormattedID) must be specified. The error is raised by the line 991 of pyral/restapi.py.
How to make it work?
The solution I found was to take another approach and looping through the steps and therefore being able to retrieve the oid of each step.
[Update 14 May 2015]: A better approach is to perform 3 steps:
update of existing test steps (if any)
creation of new test steps (if needed)
deletion of extra test steps (if needed)
The program shall first identify the number of steps for each operation.
The result looks like this:
TCid = "TC1394"
#Generate random number of steps
def generate_Steps():
list_Steps=[]
import random
n_steps=random.randrange(1,15)
for i in range(n_steps):
Step={'StepIndex':i+1}
Step['Input']="Step Input for step %d" % (i+1)
Step['ExpectedResult']="Expected Result for step %d" % (i+1)
list_Steps.append(Step)
print "Using random list of %d Test Steps" % (n_steps)
return list_Steps
#Update steps
def update_TestSteps(TCid, Steps):
try:
#Get number of existing steps
testcase=rally.get('TestCase', query='FormattedID = %s' % TCid, instance=True)
print "Updating steps for Test Case %s" % testcase.FormattedID
list_steps=sorted(testcase.Steps, key=lambda step: step.StepIndex)
#Calculate what to do on the steps (how many to update, create, or delete)
nb_steps = { 'Rally':len(testcase.Steps), 'HTML':len(Steps) }
nb_steps['toUpdate'] = min(nb_steps['Rally'], nb_steps['HTML'])
nb_steps['toCreate'] = nb_steps['HTML'] - nb_steps['toUpdate']
nb_steps['toDelete'] = nb_steps['Rally'] - nb_steps['toUpdate']
#Update content of existing steps with steps from test case
for StepIndex in range(nb_steps['toUpdate']):
step=list_steps[StepIndex]
teststep_fields = Steps[StepIndex]
(teststep_fields['TestCase'], teststep_fields['ObjectID']) = (testcase.ref, step.oid)
teststep = rally.update('TestCaseStep', teststep_fields)
#Create new test steps when required
for StepIndex in range(nb_steps['toCreate']):
teststep_fields = Steps[StepIndex+nb_steps['toUpdate']]
teststep_fields['TestCase'] = testcase.ref
teststep = rally.put('TestCaseStep', teststep_fields)
#Delete extra test steps
for StepIndex in range(nb_steps['toDelete']):
step=list_steps[StepIndex+nb_steps['toUpdate']]
rally.delete('TestCaseStep', step.oid)
#Print message for end of test step update
message="Updated test steps for TestCase %s" % testcase.FormattedID
message+=" (steps created: {toCreate}, updated: {toUpdate}, deleted: {toDelete})".format(**nb_steps)
print message
except RallyRESTAPIError, details:
sys.stderr.write('Rally Error during update of Test Step: %s \n\n' % details)
#Update random list of Steps
update_TestSteps(TCid, generate_Steps())
There are a lot of threads with questions similar to mine, but I can't find the correct answer.
My goal is to create an if statement that compares the time now to a schedule (the schedule defined by a start time and end time).
I have it working if I put specific numbers in for the schedule, but I need to pass variables into my statement seeing that the schedule is not going to be static.
What I have so far:
import time as sleeptime
from datetime import datetime, time
schedule_list = []
def scheduler():
conn = pymysql.connect(host='myhost', db='test', user='1234', passwd='123456', autocommit = True)
cur = conn.cursor()
query = ("SELECT startTimehour, startTimeminute, endTimehour, endTimeminute FROM schedule WHERE hwID = %s")
print query
cur.execute(query, (number))
for row in cur:
print row
door_schedule_list.append(row)
cur.close()
conn.close()
if len(door_schedule_list) > 0:
start_time_hour = door_schedule_list[0][0]
start_time_minute = door_schedule_list[0][1]
end_time_hour = door_schedule_list[0][2]
end_time_minute = door_schedule_list[0][3]
print start_time_hour
print start_time_minute
print end_time_hour
print end_time_minute
while True:
now = datetime.now()
#print (door_schedule_list)
#starttime = time(startTimehour, startTimeminute)
if time("%d","%d") <= now.time() <= time("%d","%d") % (start_time_hour, start_time_minute, end_time_hour, end_time_minute):
print "Schedule active"
sleeptime.sleep(20)
else:
print "Schedule Inactive"
sleeptime.sleep(20)
If there is an easier way to accomplish my goal, please let me know. Otherwise how can I fix the error.
When you do:
if time("%d","%d") <= now.time() <= time("%d","%d") % (start_time_hour, start_time_minute, end_time_hour, end_time_minute)
the % operator its not doing what you think it should do.
Its not the same:
time("%d" % 5, "%d" % 4)
than
time("%d", "%d") % (5, 4)
the last line will complains with the error: an integer is required.
Also you can:
hours = 5
min = 4
time(hours, min)
So you can change the line to:
if time(start_time_hour, start_time_minute) <= now.time() <= time(end_time_hour, end_time_minute)
This is copy of the code in mining the social web book.
I am a new in this field and with redis too. I want to understand what does $ mean in this context. Also the print with %s, What does it mean?
This is the source code below (from: https://github.com/ptwobrussell/Mining-the-Social-Web):
import sys
import redis
from twitter__util import getRedisIdByScreenName
# A pretty-print function for numbers
from twitter__util import pp
r = redis.Redis()
screen_names=['user1','user2']
def friendsFollowersInCommon(screen_names):
r.sinterstore('temp$friends_in_common',
[getRedisIdByScreenName(screen_name, 'friend_ids')
for screen_name in screen_names]
)
r.sinterstore('temp$followers_in_common',
[getRedisIdByScreenName(screen_name, 'follower_ids')
for screen_name in screen_names]
)
print 'Friends in common for %s: %s' % (', '.join(screen_names),
pp(r.scard('temp$friends_in_common')))
print 'Followers in common for %s: %s' % (', '.join(screen_names),
pp(r.scard('temp$followers_in_common')))
# Clean up scratch workspace
r.delete('temp$friends_in_common')
r.delete('temp$followers_in_common')
if __name__ == "__main__":
if len(screen_names) < 2:
print >> sys.stderr, "Please supply at least two screen names."
sys.exit(1)
friendsFollowersInCommon(screen_names[1:])
$ symbol is just a part of key name. It separates name parts. I usually use : for the same purpose (e.g. users:123)
%s part is python's string formatting.