-1

I'm making an IRC bot for my network. To make the code cleaner, I am defining functions in modules. All these modules are in a folder called "plugins". One module say calls the function sendMsg and fails because it's trying to run a function defined in the main program. I also want to have this module to be able to access variables defined in the main program after the program has started.

import socket
import time
import re

from plugins.say import *

host = "irc.somenetwork.net"
port = 6667
nick = "ircbot"
channels = "##bottesting"
s = socket.socket()

def connect():
   s.connect((host, port))
   s.send("NICK %s\r\n" % nick)
   s.send("USER %s %s nul :%s\r\n" % (nick, nick, nick))
   time.sleep(3)
   s.send("JOIN %s\r\n" % channels)
   time.sleep(3)

def sendMsg(chan, msgSend):
   s.send("PRIVMSG %s :%s\r\n" % (chan,msgSend))
#   print "Sending message \"%s\" to channel/user \"%s\"" % (msgSend, chan)

def quitServ(quitMsg="m8bot"):
   s.send("QUIT %s\r\n" % quitMsg)

connect()

while 1:
   msgRaw = s.recv(1024)
   print msgRaw
   if msgRaw == "":
      break
   if "PING" in msgRaw:
      print "Pong!"
      PONG = msgRaw.split(' ')
      PONG[0] = PONG[0].replace('PING','PONG')
      PONG = ' '.join(PONG)
      s.send("%s\r\n" % PONG)
   if "PRIVMSG" in msgRaw:
#      print "PRIVMSG detected"
      user = ''.join(re.compile("(?<=:).{0,}(?=.{0,}!)").findall(msgRaw.split(' ')[0]))
      channel = msgRaw.split(' ')[2]
      command = (' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[0]
      msg = ''.join((' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[1:]).replace("\r\n","")

      if not "#" in channel:
         channel = user
      print "Nick: %s\nChannel: %s\nCommand: %s\nMsg: %s" % (user,channel,command,msg)
      if ".quit" in command:
         if msg:
            quitServ(str(msg))
         else:
            quitServ()
      if ".hello" in command:
#         print "Attempting to send Hello World message."
         sendMsg(channel, "Hello World!")
      if ".say" in command:
         say(msg)

quitServ()

This is my program. function say() is as follows:

def say(msg):
   sendMsg(channel, "You said: %s" % msg)

I can see what the problem is, but I don't know how I would fix this. Feedback appreciated :)

-Nia

NiaKitty
  • 93
  • 4

1 Answers1

0

Try import __main__ in your say.py. And then your say function should look something like this:

def say():
   __main__.sendMsg(channel, "You said: %s" % msg)

But this is not a best solution. Just solution with less code changes.