From Your mom, 6 Years ago, written in Python.
Embed
  1. from twisted import __version__ as twistedversion
  2. from twisted.words.protocols import irc
  3. from twisted.internet import protocol, reactor, task
  4. from Queue import Queue
  5. import omegle
  6. import re
  7. import sys
  8. import os
  9. import logging
  10. import platform
  11. import random
  12. import optparse
  13. import time
  14. import datetime
  15. import binascii
  16. try: import json
  17. except: import simplejson as json
  18.  
  19. from twisted.python import log
  20. log.startLogging(sys.stdout)
  21.  
  22. _contcodes = re.compile(r"(?:\x02|\x03(?:\d{1,2}(?:,\d{1,2})?)?|\x0f|\x1f|\x1d)") # control codes
  23. _places = ['amsterdam', 'athens', 'atlanta', 'austin', 'baltimore', 'bangkok', 'barcelona', 'beijing', 'berlin', 'birmingham', 'boston', 'brighton', 'brisbane', 'bristol', 'brussels', 'buenos aires', 'calgary', 'charlotte', 'chicago', 'cleveland', 'cologne', 'columbus', 'copenhagen', 'dallas/fw', 'denver', 'detroit', 'dubai', 'dublin', 'edinburgh', 'edmonton', 'frankfurt', 'geneva', 'hamburg', 'helsinki', 'hong kong', 'honolulu', 'houston', 'indianapolis', 'johannesburg', 'kansas city', 'kuala lumpur', 'las vegas', 'lisbon', 'london', 'la', 'louisville', 'madrid', 'manchester', 'melbourne', 'memphis', 'mexico city', 'miami', 'milan', 'milwaukee', 'twin cities', 'montreal', 'mumbai', 'munich', 'nashville', 'new haven', 'new orleans', 'nyc', 'oklahoma city', 'omaha', 'orlando', 'oslo', 'ottawa', 'paris', 'park city', 'philly', 'phoenix', 'pittsburgh', 'portland', 'prague', 'providence', 'raleigh-durham', 'reykjavik', 'richmond', 'rio de janeiro', 'rome', 'sacramento', 'salt lake city', 'san antonio', 'san diego', 'sf', 'sao paulo', 'seattle', 'seoul', 'shanghai', 'singapore', 'st. louis', 'stockholm', 'sydney', 'tampa', 'tel aviv', 'tokyo', 'toronto', 'tucson', 'vancouver', 'vienna', 'd.c.', 'wellington', 'zurich']
  24.  
  25. def connectedonly(fn):
  26.     def wrapper(self, *args):
  27.         if not self.ctx["clients"]:
  28.             self.msg(self.context, "\x01ACTION \x035is not connected to Omegle.\x01")
  29.         else:
  30.             fn(self, *args)
  31.     return wrapper
  32.  
  33. class OmegleWebClient(omegle.OmegleChat):
  34.     ctx = property(lambda self: self.target.contexts[self.context])
  35.    
  36.     def __init__(self, target, context):
  37.         self.target = target
  38.         self.context = context
  39.         self.q = Queue()
  40.         self.silent = False
  41.        
  42.         self.lc = task.LoopingCall(self.on_loop)
  43.        
  44.         omegle.OmegleChat.__init__(self, config["pollinterval"], "", "omegle.com")
  45.    
  46.     def on_message(self, message):
  47.         while True:
  48.             if False not in map(lambda x: hasattr(x, "id") and x.is_confirmed, self.ctx["clients"]):
  49.                 reactor.callFromThread(self.target.emitmsg, self, message)
  50.                 break
  51.    
  52.     def on_connect(self):
  53.         self.lc.start(config["pollinterval"])
  54.         reactor.callFromThread(self.target.log, self.context, self, "E", "connect", None)
  55.    
  56.     def on_loop(self):
  57.         if hasattr(self, "is_confirmed") and self.is_confirmed and not self.q.empty():
  58.             try:
  59.                 omegle.OmegleChat.send(self, self.q.get_nowait())
  60.             except:
  61.                 reactor.callFromThread(self.target.loseclient, self, "Transport error")
  62.    
  63.     def on_disconnect(self):
  64.         reactor.callFromThread(self.target.loseclient, self)
  65.    
  66.     def on_recaptcha(self):
  67.         reactor.callFromThread(self.target.msg, self.context, "\x01ACTION \x035requires the following CAPTCHA to be solved: http://www.google.com/recaptcha/api/image?c=%s\x01" % self.captcha)
  68.         reactor.callFromThread(self.target.msg, self.context, "\x01ACTION \x035requests that you transmit your answer with: %sr %s <your response>\x01" % (config["prefix"].encode("utf-8"), self.id))
  69.    
  70.     def on_recaptcha_rejected(self):
  71.         reactor.callFromThread(self.target.loseclient, self, "Failed CAPTCHA")
  72.    
  73.     def send(self, message):
  74.         self.q.put_nowait(message)
  75.        
  76. class OmegleIRCBot(irc.IRCClient):
  77.    
  78.     # CONTEXT
  79.     ctx = property(lambda self: self.contexts[self.context])
  80.    
  81.     # ALIASES
  82.     cmd_c = property(lambda self: self.cmd_connect)
  83.     cmd_co = property(lambda self: self.cmd_connect)
  84.     cmd_d = property(lambda self: self.cmd_disconnect)
  85.     cmd_dc = property(lambda self: self.cmd_disconnect)
  86.     cmd_r = property(lambda self: self.cmd_captcha)
  87.     cmd_stfu = property(lambda self: self.cmd_silence)
  88.     cmd_s = property(lambda self: self.cmd_sayas)
  89.     cmd_sa = property(lambda self: self.cmd_sayas)
  90.     cmd_say = property(lambda self: self.cmd_sayas)
  91.     cmd_st = property(lambda self: self.cmd_sayto)
  92.    
  93.     # COMMANDS
  94.     @connectedonly
  95.     def cmd_asl(self, horny = "horny", *args):
  96.         age = random.randrange(16, 26)
  97.         sex = (lambda: "m", lambda: "f")[horny == "horny"]()
  98.         location = _places[random.randrange(0, len(_places))]
  99.         self.sendannounce("%d/%s/%s" % (age, sex, location))
  100.    
  101.     def cmd_help(self, *args):
  102.         self.msg(self.context, "Nothing of your buisness you faggot gtfo!")
  103.    
  104.     def cmd_connect(self, numclients = 1, *args):
  105.         if self.ctx["pair"] and len(self.ctx["clients"]) == 2:
  106.             self.msg(self.context, "\x01ACTION \x035cannot add clients manually in pairing mode.\x01")
  107.             return
  108.         if not self.ctx["clients"]:
  109.             self.ctx["confid"] = "%08x" % (binascii.crc32("%f%f%f" % (random.random(), time.time(), random.random())) & 0xffffffff)
  110.         cids = []
  111.         try:
  112.             numclients = int(numclients)
  113.         except: numclients = 1
  114.         for i in xrange(0, numclients):
  115.             if len(self.ctx["clients"]) >= config["maxclients"]:
  116.                 break
  117.             client = OmegleWebClient(self, self.context)
  118.             self.ctx["clients"].append(client)
  119.             client.start()
  120.             self.cids = cids
  121.             cids.append(client.id)
  122.            
  123.         if cids:
  124.             self.msg(self.context, "3[09%s3]3 Connected!" % "".join(cids))
  125.             if self.ctx["aware"]:
  126.                 map(lambda x: x.send("[Info] %d client(s) joined, ID(s) are %s." % (len(cids), ", ".join(cids))), filter(lambda x: x.id not in cids, self.ctx["clients"]))
  127.         else:
  128.             self.msg(self.context, "\x01ACTION \x035cannot add any more clients.\x01")
  129.    
  130.     def cmd_count(self, *args):
  131.         if len(self.ctx["clients"]):
  132.             self.msg(self.context, "\x01ACTION \x035currently has %d client(s) (ID(s) are: %s).\x01" % (len(self.ctx["clients"]), ", ".join(map(lambda x: x.id, self.ctx["clients"]))))
  133.         else:
  134.             self.msg(self.context, "\x01ACTION \x035currently has no clients.\x01")
  135.    
  136.     @connectedonly
  137.     def cmd_kill(self, cid = None, *args):
  138.         if not cid:
  139.             self.msg(self.context, "\x01ACTION \x035requires a client ID argument.\x01")
  140.             return
  141.         pclients = filter(lambda x: re.match(cid, x.id), self.ctx["clients"])
  142.         if pclients:
  143.             for client in pclients:
  144.                 self.loseclient(client, "Killed by host")
  145.         else:
  146.             self.msg(self.context, "\x01ACTION \x035found no such clients to kill.\x01")
  147.    
  148.     @connectedonly
  149.     def cmd_disconnect(self, numclients = 0, *args):
  150.         cids = []
  151.         try:
  152.             numclients = int(numclients)
  153.         except: numclients = config["maxclients"]
  154.         if numclients == 0: numclients = config["maxclients"]
  155.         if self.ctx["pair"]:
  156.             numclients = config["maxclients"]
  157.         for i in xrange(0, numclients):
  158.             if not self.ctx["clients"]:
  159.                 break
  160.             cids.append(self.ctx["clients"][0].id)
  161.             self.log(self.context, self.ctx["clients"][0], "E", "disconnect", None)
  162.             try:
  163.                 self.ctx["clients"][0].disconnect()
  164.             except: pass
  165.             try:
  166.                 del self.ctx["clients"][0]
  167.             except: pass
  168.         if cids:
  169.             self.msg(self.context, "\x01ACTION \x035has removed from %d client(s) from conference %s (ID(s) were: %s).\x01" % (len(cids), self.ctx["confid"], ", ".join(cids)))
  170.             if self.ctx["aware"]:
  171.                 map(lambda x: x.send("[Info] %d client(s) forcequit IRC-side, ID(s) were %s." % (len(cids), ", ".join(cids))), filter(lambda x: x.id not in cids, self.ctx["clients"]))
  172.             if not self.ctx["clients"]:
  173.                 self.ctx["confid"] = None
  174.             if self.ctx["pair"]:
  175.                 self.cmd_connect(2)
  176.         else:
  177.             self.msg(self.context, "\x01ACTION \x035cannot disconnect non-existent clients.\x01")
  178.    
  179.     @connectedonly
  180.     def cmd_sayas(self, *message):
  181.         cid = self.cids[-1]
  182.         if not cid:
  183.             self.msg(self.context, "\x01ACTION \x035requires a client ID argument.\x01")
  184.             return            
  185.         message = " ".join(message).strip()
  186.         if not message:
  187.             self.msg(self.context, "\x01ACTION \x035requires a message to send. %s\x01" % self.cid)
  188.             return
  189.         pclients = filter(lambda x: re.match(cid, x.id), self.ctx["clients"])
  190.         if not pclients:
  191.             self.msg(self.context, "\x01ACTION \x035found no such client to say as.\x01")
  192.             return
  193.         for client in pclients:
  194.             self.log(self.context, client, "M", "sayas", "".join(message))
  195.             self.emitmsg(client, message)
  196.    
  197.     @connectedonly
  198.     def cmd_sayto(self, cid = None, *message):
  199.         if not cid:
  200.             self.msg(self.context, "\x01ACTION \x035requires a client ID argument.\x01")
  201.             return
  202.         message = " ".join(message).strip()
  203.         if not message:
  204.             self.msg(self.context, "\x01ACTION \x035requires a message to send.\x01")
  205.             return
  206.         if self.ctx["aware"]:
  207.             self.msg(self.context, "\x01ACTION \x035cannot use say to in aware mode.\x01") # awwz
  208.             return        
  209.         pclients = filter(lambda x: re.match(cid, x.id), self.ctx["clients"])
  210.         if pclients:    
  211.             for client in pclients:
  212.                 self.log(self.context, None, "M", "sayto", "%s:%s" % (client.id, message))
  213.                 self.msg(self.context, "\x02OUTGOING TO %s:\x02 %s" % (client.id, message))
  214.                 client.send(message)
  215.         else:
  216.             self.msg(self.context, "\x01ACTION \x035found no such client to say to.\x01")
  217.    
  218.     @connectedonly
  219.     def cmd_captcha(self, cid = None, *response):
  220.         if not cid:
  221.             self.msg(self.context, "\x01ACTION \x035requires a client ID argument.\x01")
  222.             return
  223.         captcha = " ".join(response)
  224.         for client in filter(lambda x: re.match(cid, x.id), self.ctx["clients"]):
  225.             client.captchaConfirm(captcha)
  226.             self.msg(self.context, "\x01ACTION \x035is confirming CAPTCHA for %s with \"%s\".\x01" % (client.id, captcha))
  227.  
  228.     def cmd_aware(self, *args):
  229.         if self.ctx["aware"]:
  230.             self.ctx["aware"] = False
  231.             self.log(self.context, None, "S", "aware", "")
  232.             self.msg(self.context, "\x01ACTION \x035will no longer report multiple clients Omegle-side.\x01")
  233.         else:
  234.             self.ctx["aware"] = True
  235.             self.log(self.context, None, "S", "aware", "")
  236.             self.msg(self.context, "\x01ACTION \x035will now report multiple clients Omegle-side.\x01")
  237.  
  238.     def cmd_mute(self, *args):
  239.         if self.ctx["mute"]:
  240.             self.ctx["mute"] = False
  241.             self.log(self.context, None, "S", "mute", "")
  242.             self.msg(self.context, "\x01ACTION \x035will now accept messages IRC-side.\x01")
  243.         else:
  244.             self.ctx["mute"] = True
  245.             self.log(self.context, None, "S", "mute", "")
  246.             self.msg(self.context, "\x01ACTION \x035will no longer accept messages IRC-side.\x01")
  247.    
  248.     def cmd_pair(self, *args):
  249.         if self.ctx["pair"]:
  250.             self.ctx["pair"] = False
  251.             self.log(self.context, None, "S", "pair", "")
  252.             self.msg(self.context, "\x01ACTION \x035will no longer use pairing.\x01")
  253.         else:
  254.             self.ctx["pair"] = True
  255.             self.log(self.context, None, "S", "pair", "")
  256.             self.msg(self.context, "\x01ACTION \x035will now use pairing.\x01")
  257.             self.cmd_connect(2) # pair 2 clients to start off with
  258.    
  259.     @connectedonly
  260.     def cmd_silence(self, cid = None, *args):
  261.         if not cid:
  262.             self.msg(self.context, "\x01ACTION \x035requires a client ID argument.\x01")
  263.             return
  264.         pclients = filter(lambda x: re.match(cid, x.id), self.ctx["clients"])
  265.         if pclients:
  266.             silenced = []
  267.             unsilenced = []
  268.             for client in pclients:
  269.                 if client.silent:
  270.                     client.silent = False
  271.                     self.log(self.context, client, "S", "silence", "")
  272.                     unsilenced.append(client.id)
  273.                 else:
  274.                     client.silent = True
  275.                     self.log(self.context, client, "S", "silence", "")
  276.                     silenced.append(client.id)
  277.             if silenced:
  278.                 self.msg(self.context, "\x01ACTION \x035has silenced %d client(s) (ID(s) are: %s).\x01" % (len(silenced), ", ".join(silenced)))
  279.             if unsilenced:
  280.                 self.msg(self.context, "\x01ACTION \x035has unsilenced %d client(s) (ID(s) are: %s).\x01" % (len(unsilenced), ", ".join(unsilenced)))
  281.         else:
  282.             self.msg(self.context, "\x01ACTION \x035found no such client to mode change.\x01")
  283.    
  284.     # FUNCTIONS
  285.     def loseclient(self, client, reason = "Remote disconnect", repair = True):
  286.         if not hasattr(client, "lost") or not client.lost:
  287.             self.log(client.context, client, "E", "loseclient", reason)
  288.             client.lost = True
  289.             try:
  290.                 client.lc.stop()
  291.             except AssertionError: pass
  292.             self.msg(client.context, "\x01ACTION \x035has lost client %s from Omegle (%s).\x01" % (client.id, reason))
  293.             if client.ctx["aware"]:
  294.                 for c in filter(lambda x: x is not client, client.ctx["clients"]):
  295.                     c.send("[Info] Client %s has been lost (%s)." % (client.id, reason))
  296.             try:
  297.                 try:
  298.                     client.disconnect()
  299.                 except:
  300.                     pass
  301.                 del client.ctx["clients"][client.ctx["clients"].index(client)]
  302.             except ValueError:
  303.                 pass
  304.             if not client.ctx["clients"]:
  305.                 client.ctx["confid"] = None
  306.             if client.ctx["pair"]:
  307.                 for c in client.ctx["clients"]:
  308.                     self.loseclient(c, "Pairing ended", False)
  309.                 if repair:
  310.                     tempcontext = self.context
  311.                     self.context = client.context
  312.                     self.cmd_connect(2)
  313.                     self.context = tempcontext
  314.    
  315.     def emitmsg(self, client, msg):
  316.         if not client.id: return # none of the None nastiness
  317.         msg = msg.strip()
  318.         if not client.silent:
  319.             for c in filter(lambda x: x is not client, client.ctx["clients"]):
  320.                 if self.ctx["aware"]:
  321.                     c.send("[%s:Omegle] %s" % (client.id, msg))
  322.                 else:
  323.                     c.send(msg)
  324.         lines = msg.encode("utf-8").replace("\r\n", "\n").replace("\r", "\n").split("\n")
  325.         if len(lines) > config["omegleflood"]: # flooding
  326.             self.loseclient(client, "Excess flood")
  327.         else:
  328.             for m in lines:
  329.                 self.log(client.context, client, "M", "msg", m)    
  330.                 self.msg(client.context, "\x02[%s]\x02 %s" % (client.id, m))
  331.    
  332.     def sendannounce(self, msg):
  333.         self.log(self.context, None, "M", "announce", msg)
  334.         self.msg(self.context, "\x02OUTBOUND:\x02 %s" % msg)
  335.         map(lambda x: x.send(msg), self.ctx["clients"])
  336.    
  337.     def log(self, context, client, rtype, method, msg):
  338.         if self.contexts[context]["confid"] and self.factory.dbconn:
  339.             self.factory.dbconn.runQuery("INSERT INTO `%s` (timestamp, confid, mute, aware, pair, silent, clientid, medium, type, method, message) VALUES(NOW(), %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s)" % _mysql.escape_string(context[1:]), (self.contexts[context]["confid"], (lambda: "N", lambda: "Y")[self.contexts[context]["mute"]](), (lambda: "N", lambda: "Y")[self.contexts[context]["aware"]](), (lambda: "N", lambda: "Y")[self.contexts[context]["pair"]](), (lambda: "N", lambda: "Y")[(lambda: False, lambda: client.silent)[isinstance(client, OmegleWebClient)]()](), (lambda: client, lambda: client.id)[isinstance(client, OmegleWebClient)](), (lambda: "IRC", lambda: "Omegle")[isinstance(client, OmegleWebClient)](), rtype, method, msg))
  340.    
  341.     # EVENTS
  342.     def __init__(self):
  343.         self.contexts = {}
  344.         self.context = None
  345.         self.lineRate = config["linerate"]
  346.         self.versionName = "OmegleIRC"
  347.         self.versionNum = "0.1"
  348.         self.versionEnv = "%s/%s+Twisted/%s" % (platform.uname()[0], platform.uname()[2], twistedversion)
  349.         self.realname = config["realname"].encode("utf-8")
  350.         self.username = config["username"].encode("utf-8")
  351.    
  352.     def connectionMade(self):
  353.         self.nickname = config["nickname"].encode("utf-8")
  354.         irc.IRCClient.connectionMade(self)
  355.    
  356.     def irc_RPL_WELCOME(self, prefix, params):
  357.         if config["nspass"]:
  358.             self.msg("NickServ", "GHOST %s %s" % (config["nickname"].encode("utf-8"), config["nspass"].encode("utf-8")))
  359.             self.msg("NickServ", "IDENTIFY %s" % config["nspass"].encode("utf-8"))
  360.         for c in config["channels"]:
  361.             self.join(c.encode("utf-8"))
  362.    
  363.     def connectionLost(self, reason):
  364.         for c in map(lambda x: x["clients"], self.contexts.values()):
  365.             try:
  366.                 c.disconnect()
  367.             except: pass
  368.    
  369.     def joined(self, channel):
  370.         self.contexts[channel.lower()] = {
  371.             "clients"    :    [],
  372.             "aware"        :    False,
  373.             "mute"        :    False,
  374.             "pair"        :    False,
  375.             "confid"    :    None
  376.         }
  377.         self.context = channel.lower()
  378.         if self.factory.dbconn:
  379.             self.factory.dbconn.runQuery("""\
  380. CREATE TABLE IF NOT EXISTS `%s`
  381. (
  382.    timestamp DATETIME,
  383.    confid VARCHAR(8),
  384.    mute ENUM("N", "Y"),
  385.    aware ENUM("N", "Y"),
  386.    pair ENUM("N", "Y"),
  387.    silent ENUM("N", "Y"),
  388.    clientid VARCHAR(32),
  389.    medium ENUM("IRC", "Omegle"),
  390.    type ENUM("E", "M", "S"),
  391.    method VARCHAR(32),
  392.    message TEXT
  393. );\
  394. """ % _mysql.escape_string(self.context[1:]))
  395.         self.log(self.context, "", "E", "joined", channel)
  396.    
  397.     def privmsg(self, user, channel, msg):
  398.         nick = user.split("!")[0] # hostname and ident are superfluous
  399.         self.context = channel.lower()
  400.         if msg[:len(config["invisprefix"])] == config["invisprefix"]: return # gtfo
  401.         if not channel.lower() in map(lambda x: x.lower(), self.contexts.keys()): return # no idea how you're here but gtfo as well
  402.         msg = _contcodes.sub("", msg)
  403.         if msg.lower()[:len(config["prefix"])] == config["prefix"]:
  404.             argv = msg[len(config["prefix"]):].split(" ")
  405.             if hasattr(self, "cmd_%s" % argv[0].lower()):
  406.                 getattr(self, "cmd_%s" %  argv[0].lower())(*argv[1:])
  407.         elif not self.ctx["mute"]:
  408.             if self.ctx["clients"]:
  409.                 if msg[:8].lower() == "\x01action " and msg[-1] == "\x01":
  410.                     msg = "*%s*" % msg[8:-1]
  411.                 self.log(self.context, nick, "M", "msg", msg)
  412.                 if self.ctx["aware"]:
  413.                     map(lambda x: x.send("[%s:IRC] %s" % (nick, msg)), self.ctx["clients"])
  414.                 else:
  415.                     map(lambda x: x.send(msg), self.ctx["clients"])
  416.    
  417.     def action(self, user, channel, data):
  418.         self.privmsg(user, channel, "\x01ACTION %s\x01" % data)
  419.    
  420. class OmegleBotFactory(protocol.ClientFactory):
  421.     protocol = OmegleIRCBot
  422.    
  423.     def __init__(self):
  424.         if config["mysqlconns"]:
  425.             self.dbconn = adbapi.ConnectionPool("MySQLdb", \
  426.                 host = (lambda: None, lambda: config["mysqlconns"]["host"])["host" in config["mysqlconns"].keys()](), \
  427.                 user = (lambda: None, lambda: config["mysqlconns"]["username"])["username" in config["mysqlconns"].keys()](), \
  428.                 passwd = (lambda: None, lambda: config["mysqlconns"]["password"])["password" in config["mysqlconns"].keys()](), \
  429.                 db = (lambda: None, lambda: config["mysqlconns"]["database"])["database" in config["mysqlconns"].keys()](), \
  430.                 port = (lambda: None, lambda: config["mysqlconns"]["port"])["port" in config["mysqlconns"].keys()](), \
  431.             )
  432.        
  433.         else:
  434.             self.dbconn = None
  435.    
  436.     def clientConnectionLost(self, connector, reason):
  437.         print "Lost connection (%s), reconnecting." % (reason,)
  438.         connector.connect()
  439.  
  440.     def clientConnectionFailed(self, connector, reason):
  441.         print "Could not connect: %s" % (reason,)
  442.  
  443. if __name__ == "__main__":
  444.     arghelp = {
  445.         "nickname"        :    "nickname to use",
  446.         "realname"        :    "real name in whois",
  447.         "username"        :    "fake ident",
  448.         "nspass"        :    "nickserv password",
  449.         "server"        :    "irc server",
  450.         "port"            :    "server port",
  451.         "channels"        :    "list of channels, separated by commas",
  452.         "prefix"        :    "command prefix",
  453.         "invisprefix"    :    "invisible prefix",
  454.         "maxclients"    :    "maximum clients per chan",
  455.         "pollinterval"    :    "interval to poll",
  456.         "linerate"        :    "twisted line rate",
  457.         "omegleflood"    :    "maximum lines for an omegle client",
  458.         "mysqlconns"    :    "mysql connection string, in json: \"{'host':<hostname>,'port':<port>,'database':<database>,'username':<username>, 'password':<password>}\"",
  459.         "pidfile"        :    "pidfile to save the pid to",
  460.         "foreground"    :    "run in foreground (accepts true/false)"
  461.     }
  462.     parser = optparse.OptionParser()
  463.     parser.add_option("-c", "--config", help="configuration file", metavar="FILE", dest="config")
  464.     for v in arghelp.keys():
  465.         parser.add_option("", "--%s" % v, help=arghelp[v], metavar="VALUE", dest=v)
  466.     (options, args) = parser.parse_args()
  467.     config = json.load(open((lambda: "bot.json", lambda: options.config)[bool(hasattr(options, "config") and options.config)]()))
  468.    
  469.     for o in options.__dict__.iteritems(): # doin it rong
  470.         if o[0] == "config" or o[1] is None: continue
  471.         if o[0] == "channels":
  472.             config[o[0]] = o[1].split(",")
  473.         elif o[0] == "foreground":
  474.             config[o[0]] = (o[1].lower() == "true")
  475.         elif o[0] == "mysqlconns":
  476.             config[o[0]].update(json.loads(o[1]))
  477.         else:
  478.             config[o[0]] = o[1]
  479.    
  480.     if config["mysqlconns"]:
  481.         from twisted.enterprise import adbapi
  482.         import _mysql
  483.    
  484.     if not config["foreground"]:
  485.         try:
  486.             pid = os.fork()
  487.             if pid > 0:
  488.                 sys.exit(0)
  489.         except OSError, e:
  490.             print >>sys.stderr, "On fork #1: %s" % str(e)
  491.             sys.exit(1)
  492.  
  493.         try:
  494.             pid = os.fork()
  495.             if pid > 0:
  496.                 pidfile = open(config["pidfile"], "w")
  497.                 pidfile.write(str(pid))
  498.                 pidfile.close()
  499.                 sys.exit(0)
  500.         except OSError, e:
  501.             print >>sys.stderr, "On fork #2: %s" % str(e)
  502.             sys.exit(1)    
  503.    
  504.     reactor.connectTCP(config["server"], config["port"], OmegleBotFactory())
  505.     reactor.run()
  506.  

Replies to Untitled rss

Title Name Language When
RE: Untitled anonymous python 6 Years ago.