python - Making a module use functions and variables defined within the main program -
i'm making irc bot network. make code cleaner, defining functions in modules. these modules in folder called "plugins". 1 module say calls function sendmsg , fails because it's trying run function defined in main program. want have module able access variables defined in main program after program has started.
import socket import time import re 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\" 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 send hello world message." sendmsg(channel, "hello world!") if ".say" in command: say(msg) quitserv()
this program. function say() follows:
def say(msg): sendmsg(channel, "you said: %s" % msg)
i can see problem is, don't know how fix this. feedback appreciated :)
-nia
try import __main__
in say.py. , function should this:
def say(): __main__.sendmsg(channel, "you said: %s" % msg)
but not best solution. solution less code changes.
Comments
Post a Comment