PING! PONG!
30 April 2006 16:00When I used mIRC for IRC, I had a list of pongs (replies to pings) that were somewhat randomly chosen to send back to whoever pinged me. Then I switched to x-chat and needed a script to the same thing. I didn't snag one from anyone, nor did I write one... until recently.
I've been playing with Python a bit and this past week found out how to open, read, and close files with Python. After a while I had the core of the script done, but needed to make it work with x-chat.
Yesterday evening I started playing with the x-chat python stuff and managed to send commands to x-chat. This morning I managed to get x-chat to load and run a script. With help from
jmaynard I managed to get it to be useful.
The result probably isn't ideal, but this is the first bit of working (as in, it has a job and does it and isn't just an example) Python I've written. It uses the same style file as mIRC does: The first line is the number of remaining lines, each of the remaining lines is a possible reply. For anyone desperate enough to use this, remember to change the line with the file location.
#! /usr/bin/env python
#
# 29 April 2006
__module_name__ = "ctcphandler"
__module_version__ = "0.1"
__module_description__ = "CTCP Handler - Pong Replier"
import xchat
import random
def ctcp_cb(word, word_eol, userdata): # Handle trapped CTCP events
mynick = xchat.get_info('nick') # Get my current nick
recvdcmd = word[0].split()[0] # Split out just the first part (so PING 240400969 is only PING)
recvdnick = word[1] # Get sender's nick
if "PING"==recvdcmd: # Handle PING
f=open('/home/vakko/.xchat2/pongs.txt','r') # Open pongfile read-only.
maxpongs=int(f.readline()) # Read first line to get number of pongs.
pongnum=random.randint(1,maxpongs) # Generate "random" number.
i=0
for line in f: # Loop to assign selected line.
i=i+1
if pongnum==i:
pongreply=line.rstrip() # Get the pong, less any trailing whitespace.
break # Bail out of the for
else:
pongreply=mynick+" goofed and ran out of pongs!" # Handle having a number bigger than the file has lines.
f.close() # Close pong file.
response="NOTICE "+recvdnick+" "+pongreply # Build PING reply
xchat.command(response) # Send PING reply
return xchat.EAT_NONE # Let xchat handle things as normal, beyond this.
xchat.hook_print("CTCP Generic",ctcp_cb) # Trap individual generic CTCP events
xchat.hook_print("CTCP Generic to Channel",ctcp_cb) # Trap channel generic CTCP events