View Full Version : a little somethin' for jemfinch (and whoever else wants it)...
inkedmn
08-29-2002, 02:23 AM
here's the code for cfactive (checks to see what users are active here on cf.net)
#!/usr/bin/env python
import urllib
import sys
import re
def cfactive():
url = 'http://www.coderforums.net'
try:
source = urllib.urlopen(url)
except Exception:
print "error"
sys.exit(1)
html = source.read()
lines = re.sub('<.*?>', '', html)
lines = lines.split('\n')
for i in range(len(lines)):
if lines[i].strip().split(' ')[0] == 'Most':
data = lines[i+1].strip()
print data
break
enjoy :)
jemfinch
08-29-2002, 12:51 PM
It's in! The first submission from someone other than me for the bot!
Oh, it feels good to be able to put stuff in the bot without having to test and debug it myself :D
Here's what I actually put in, and my comments relating to the places I changed things. I'm getting some strange behavior, but it might just be because of the changes I made, I'll have to check.
_removeHtml = re.compile('<.*?>')
def cfactive(self, irc, msg, args):
"takes no arguments."
try:
fd = urllib2.urlopen('http://www.coderforums.net/')
except Exception, e:
self.error(debug.exnToString(e))
text = fd.read()
text = self._removeHtml.sub('', text)
lines = text.splitlines()
for i in range(len(lines) - 1):
if lines[i].strip().startswith('Most'):
self.reply(lines[i+1].strip())
self.error('The format of the page seems odd.')
I changed a few variable names; obviously, that's a personal issue, and I just wanted the variable names to match what I use in the rest of the program.
I stored my own compiled copy of the regular expression. Python keeps a cache of the most recently used compiled regexps, but I never want to rely on that, since I don't know its exact behavior.
I used the string method "splitlines" instead of splitting on a newline, since splitlines should be written in C, and thus a bit faster. It's also easier to type (for me) and obvious in its purpose. It also handles line endings other than just '\n', depending on what OS you're using.
The for loop has an off-by-one error. If the last line is the first line to start with "Most", then you'll try to reference an element not in the list and raise IndexError. I fixed that.
I changed " .split(' ')[0] == 'Most' " to ".startswith('Most') " -- I haven't checked to make sure it'll work, but from the looks of the code, there's no reason it shouldn't. That should be slightly more efficient and easier to read.
And, of course, I changed the printing error messages to send IRC messages instead :)
Thanks a bunch for the command! I look forward to getting even more commands that I didn't have to design and debug myself :) After that crazy forums.py module, I don't know how ready I am to jump back into downloading files, looking for information, and sending it back.
Jeremy
jemfinch
08-29-2002, 12:54 PM
kmj showed me my change that broke it, so I fixed it :) I left out your "break" on accident :)
Jeremy
inkedmn
08-29-2002, 01:53 PM
glad you're able to use it :)
let me know if there's anything else i can do for you...
inkedmn
08-29-2002, 02:16 PM
here's one more :)
#!/usr/bin/env python
import urllib2
import string
import sys
def stockQuote(symbol):
base = 'http://finance.yahoo.com/d/quotes.csv?s='
tail = '&f=sl1d1t1c1ohgv&e=.csv'
url = base+symbol+tail
try:
quote = urllib2.urlopen(url).read()
except Exception, e:
print e
sys.exit()
splitquote = quote.split(',')
if splitquote[1] != "0.00":
print "The current price of %s is $%s - as of %s EST, a change of %s from the last business day" % \
((splitquote[0])[1:-1] , splitquote[1], splitquote[3][1:-1], splitquote[4])
else:
print "Sorry, I couldn't find a listing for %s" % symbol.upper()
have fun :)
Strike
08-29-2002, 02:24 PM
Jemfinch, I thought you stuck to the PEP style guidelines for the most part, triple quote that docstring ;)
http://www.python.org/peps/pep-0257.html
GnuVince
08-29-2002, 04:54 PM
jemfinch: first submission for supybot was my version thingie from freshmeat which you did not take at the time since you had not implemented threaded callbacks.
GnuVince
08-29-2002, 05:52 PM
WTF is going on with Supybot? I need to start it, Ctrl-C (big callback error) and then start it again for it to work. This is dumb.
Oh and I'm testing a foldoc method.
GnuVince
08-29-2002, 06:35 PM
def _index(self, lst, element, n=1):
m = 0
for i in xrange(len(lst)):
if lst[i] == element:
m += 1
if m == n:
return i
def foldoc(self, irc, msg, args):
"<software>"
s = self.getArgs(args)
soft = '+'.join(args)
url = "http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?query=" + soft
html = urllib.urlopen(url).readlines()
if re.search('No match for', html[2]):
self.reply("%s doesn't exist on Foldoc" % args[0])
else:
start = self._index(html, '
\n', 1)
stop = self._index(html, '
\n', 2)
descr = ' '.join(html[start:stop]) # Get base description
descr = re.sub('\n', '', descr) # Remove newlines
descr = re.sub('<.*?>', '', descr) # Remove HTML tags
descr = re.sub('&.*;', '', descr) # Remove HTML tags
descr = descr.lstrip() # Remove leading white spaces
self.reply(descr)
Try this out.
jemfinch
08-29-2002, 06:36 PM
I can't do much without seeing the exception, GnuVince :)
Jeremy
GnuVince
08-29-2002, 06:38 PM
And the big bad error message:
[vince@vincent: ~/prog/supybot]% python2.2 src/bot.py
[29-Aug-2002 17:37:36] upkeep ran.
[29-Aug-2002 17:37:36] USER Barbotte 0 * :Barbotte
Irc.takeMsg throttling.
error
Python 2.2.1: /usr/bin/python2.2
Thu Aug 29 17:37:36 2002
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
/home/vince/prog/supybot/others/asynchat.py in handle_read(self=<asyncoreDrivers.AsyncoreDriver connected>)
82 data = self.recv (self.ac_in_buffer_size)
83 except socket.error, _:
84 self.handle_error()
85 return
86
self = <asyncoreDrivers.AsyncoreDriver connected>
self.handle_error = <bound method AsyncoreDriver.handle_error of <as...reDrivers.AsyncoreDriver connected at 0x825315c>>
/home/vince/prog/supybot/others/asyncore.py in recv(self=<asyncoreDrivers.AsyncoreDriver connected>, buffer_size=4096)
355 return ''
356 else:
357 raise socket.error, why
358
359 def close (self):
global socket = <module 'socket' from '/usr/lib/python2.2/socket.pyc'>
socket.error = <class socket.error>
why = <socket.error instance>
error: (111, 'Connection refused')
__doc__ =
None
__getitem__ =
<bound method error.__getitem__ of <socket.error instance at 0x81dcdd4>>
__init__ =
<bound method error.__init__ of <socket.error instance at 0x81dcdd4>>
__module__ =
'socket'
__str__ =
<bound method error.__str__ of <socket.error instance at 0x81dcdd4>>
args =
(111, 'Connection refused')
The above is a description of an error in a Python program. Here is
the original traceback:
Traceback (most recent call last):
File "others/asynchat.py", line 82, in handle_read
data = self.recv (self.ac_in_buffer_size)
File "others/asyncore.py", line 357, in recv
raise socket.error, why
error: (111, 'Connection refused')
error
Python 2.2.1: /usr/bin/python2.2
Thu Aug 29 17:37:36 2002
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
/home/vince/prog/supybot/others/asynchat.py in initiate_send(self=<asyncoreDrivers.AsyncoreDriver connected>)
216
217 except socket.error, _:
218 self.handle_error()
219 return
220
self = <asyncoreDrivers.AsyncoreDriver connected>
self.handle_error = <bound method AsyncoreDriver.handle_error of <as...reDrivers.AsyncoreDriver connected at 0x825315c>>
/home/vince/prog/supybot/others/asyncore.py in send(self=<asyncoreDrivers.AsyncoreDriver connected>, data='USER Barbotte 0 * :Barbotte\r\n')
336 return 0
337 else:
338 raise socket.error, why
339 return 0
340
global socket = <module 'socket' from '/usr/lib/python2.2/socket.pyc'>
socket.error = <class socket.error>
why = <socket.error instance>
error: (32, 'Broken pipe')
__doc__ =
None
__getitem__ =
<bound method error.__getitem__ of <socket.error instance at 0x82861ec>>
__init__ =
<bound method error.__init__ of <socket.error instance at 0x82861ec>>
__module__ =
'socket'
__str__ =
<bound method error.__str__ of <socket.error instance at 0x82861ec>>
args =
(32, 'Broken pipe')
The above is a description of an error in a Python program. Here is
the original traceback:
Traceback (most recent call last):
File "others/asynchat.py", line 213, in initiate_send
num_sent = self.send (self.ac_out_buffer[:obs])
File "others/asyncore.py", line 338, in send
raise socket.error, why
error: (32, 'Broken pipe')
Irc.takeMsg throttling.
jemfinch
08-30-2002, 12:27 AM
That looks like a network problem to me, GnuVince...I'll have to wait until I get some more instances of that problem before I really spend some time on it.
Jeremy
vBulletin® v3.7.0, Copyright ©2000-2009, Jelsoft Enterprises Ltd.