0

Implementation Bot log IRC with Python. Assalamu’alaikum. this night i wanna show you how to make a bot log for IRC with python. However, this usefull to implement in server.

Some time ago, we find tutorial how to make a simple python IRC client at there. and that script like this:

import sys
import socket
import string

HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
readbuffer=""

s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %srn" % NICK)
s.send("USER %s %s bla :%srn" % (IDENT, HOST, REALNAME))

while 1:
    readbuffer=readbuffer+s.recv(1024)
    temp=string.split(readbuffer, "n")
    readbuffer=temp.pop( )

    for line in temp:
        line=string.rstrip(line)
        line=string.split(line)

        if(line[0]=="PING"):
            s.send("PONG %srn" % line[1])

That script to simply implement how to connect IRC client with python. However, but i want make a bot log, so we have some log from my channel. but how to create it?

We have some idea. Python have once module that is "Logging", yap.. modul was designed for create a log in python.

Somebody asked “How do I write log messages to a log file and the console at the same time” in stackoverflow.com, and that awesome answer from Ricardo Altamirano, how to make it with path with logging.FileHandler method.

Okay, now we just need to combine that both methods. You can checkout this script on: https://github.com/agusmakmun/Some-Examples-of-Simple-Python-Script/blob/master/irc/bot-log-v.2.py

"""
Name             : Some Examples of Simple Python Script {BOT Log IRC}
Created By       : Agus Makmun (Summon Agus)
Blog             : bloggersmart.net - python.web.id
License          : GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Documentation    : https://github.com/agusmakmun/Some-Examples-of-Simple-Python-Script/
"""

import socket, os, time
import sys, datetime

os.environ['TZ'] = 'Asia/Jakarta' #use this if u set this bot at your server and different with your location.
time.tzset()                      #set timezone
#print time.strftime('%X %x %Z')  #test output.

server = "irc.freenode.net" #server
channel = "#channel"
botnick = "nick-name"

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "connecting to:"+server
irc.connect((server, 6667))
irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This is a fun bot!n") #user authentication
irc.send("NICK "+ botnick +"n")            #sets nick
irc.send("PRIVMSG nickserv :iNOOPErn")    #auth
irc.send("JOIN "+ channel +"n")            #join the chan
#irc.send("TOPIC "+channel+" : "+"This to change the TOPIC of channel, if u use as Admin n")

date = str(datetime.datetime.now()).split('.')[0]

import inspect
import logging, os
path = 'log-irc'

def function_logger(file_level, console_level = None):
    function_name = inspect.stack()[1][3]
    logger = logging.getLogger(function_name)
    logger.setLevel(logging.DEBUG) #By default, logs all messages

    if console_level != None:
        ch = logging.StreamHandler() #StreamHandler logs to console
        ch.setLevel(console_level)
        ch_format = logging.Formatter('%(asctime)s - %(message)s')
        ch.setFormatter(ch_format)
        logger.addHandler(ch)

    #fh = logging.FileHandler("{0}.log".format(function_name))
    fh = logging.FileHandler(os.path.join(path, str(datetime.datetime.now()).split()[0]+".log"))
    fh.setLevel(file_level)
    fh_format = logging.Formatter('%(asctime)s - %(message)s') #%(lineno)d - %(levelname)s - 
    fh.setFormatter(fh_format)
    logger.addHandler(fh)

    return logger

def irc_log():
    log_logger = function_logger(logging.DEBUG, logging.ERROR)
    #log_logger.info('info message')

    while 1:
        text1 = irc.recv(2040)
        text = [date], text1

        try:
            spl = str(text).split()
            ip = spl[2].split("/")[-1]
            info = spl[3]
            user = spl[2].split("!")[0][2:]
            msg = str(text).split(channel)[-1][2:].replace("rn')", "")

            if info == 'JOIN':
                print date, "| <"+user+"> |", ip, "| has joined", channel
                log_logger.info("<"+user+"> | "+ip+" | has joined "+channel)

            elif info == 'QUIT':
                print date, "| <"+user+"> |", ip, "| was closed."
                log_logger.info("<"+user+"> | "+ip+" | was closed.")

            elif info == 'PART':
                print date, "| <"+user+"> |", ip, "| was left."
                log_logger.info("<"+user+"> | "+ip+" | was left.")

            elif info == 'PRIVMSG':
                print date, "| <"+user+"> |", ip, "| Message:", msg
                log_logger.info("<"+user+"> | "+ip+" | Message: "+msg)

            elif text1.find('PING') != -1: #check if 'PING' is found
                irc.send('PONG ' + text1.split()[1] + 'rn') #returnes 'PONG' back to the server (prevents pinging out!)

            else:
                pass
        except:
            pass

def main():
    irc_log()
    logging.shutdown()

main()

Explanation of Script

1. Set Time Zone if you want use this bot log at your server with different location.

os.environ['TZ'] = 'Asia/Jakarta'
time.tzset()                      #set timezone
#print time.strftime('%X %x %Z')  #test output.

2. Setting configuration

server = "irc.freenode.net" #server 
channel = "#channel" 
botnick = "nick-name"

3. Change nick name

irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This is a fun bot!n") #user authentication

4. Set TOPIC on your channel, but make sure you use as Admin in your channel.

#irc.send("TOPIC "+channel+" : "+"This to change the TOPIC of channel, if u use as Admin n")

5. Path output for log

path = 'log-irc'

6. Handler your output name of log with date

fh = logging.FileHandler(os.path.join(path, str(datetime.datetime.now()).split()[0]+".log"))

Then output name of log for example like this: 2015-10-15.log

7. Pinging again if this bot have a pinging out, or something

elif text1.find('PING') != -1: #check if 'PING' is found
                irc.send('PONG ' + text1.split()[1] + 'rn') #returnes 'PONG' back to the server (prevents pinging out!)

Setting bot log as Diamond in server

You can setting it with nohup or something else that will setup diamond for your script, for example like this:

root@server:~# nohup python irc_log.py &

Hopefull can help.. angel

python

Your Answer

blog comments powered by Disqus