Advertisement
lazuli_loto

Goon Jabber Bot

Mar 13th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.78 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. SleekXMPP: The Sleek XMPP Library
  6. Copyright (C) 2010 Nathanael C. Fritz
  7. This file is part of SleekXMPP.
  8.  
  9. See the file LICENSE for copying permission.
  10. """
  11. import os
  12. import sys
  13. import traceback
  14.  
  15. import pprint
  16. import json
  17. from xml.dom.minidom import parseString
  18. import urllib2 as _urllib # So you can change version without changing code.
  19.  
  20. import datetime
  21. import logging
  22. import getpass
  23. import random
  24.  
  25. from optparse import OptionParser
  26.  
  27. #import MySQLdb as mdb
  28. import shlex # For its cool splitting thingy... http://stackoverflow.com/a/79985/211081
  29. import requests # for its super cool http shit,
  30.  
  31. import sleekxmpp
  32.  
  33.  
  34.  
  35. # Python versions before 3.0 do not use UTF-8 encoding
  36. # by default. To ensure that Unicode is handled properly
  37. # throughout SleekXMPP, we will set the default encoding
  38. # ourselves to UTF-8.
  39. if sys.version_info < (3, 0):
  40. #from sleekxmpp.util.misc_ops import setdefaultencoding
  41. sys.setdefaultencoding('utf8')
  42. else:
  43. raw_input = input
  44.  
  45. def restart_program():
  46. """Restarts the current program.
  47. Note: this function does not return. Any cleanup action (like
  48. saving data) must be done before calling this function."""
  49. python = sys.executable
  50. os.execl(python, python, * sys.argv)
  51.  
  52. def millify(n): # http://stackoverflow.com/a/3155023/211081 - stolen
  53. millnames=['','K','M','B','T']
  54. millidx=max(0,min(len(millnames)-1,
  55. int(math.floor(math.log10(abs(n))/3.0))))
  56. return '%.0f %s'%(n/10**(3*millidx),millnames[millidx])
  57.  
  58. class cache_result:
  59. def __init__ (self, f):
  60. self.f = f
  61. self.mem = {}
  62. def __call__ (self, *args, **kwargs):
  63. if (args, str(kwargs)) in self.mem:
  64. return self.mem[args, str(kwargs)]
  65. else:
  66. tmp = self.f(*args, **kwargs)
  67. self.mem[args, str(kwargs)] = tmp
  68. return tmp
  69.  
  70.  
  71. class IntelBot(sleekxmpp.ClientXMPP):
  72.  
  73. """
  74. A simple SleekXMPP bot that will greets those
  75. who enter the room, and acknowledge any messages
  76. that mentions the bot's nickname.
  77. """
  78.  
  79. def __init__(self, jid, password, room, nick):
  80. sleekxmpp.ClientXMPP.__init__(self, jid, password)
  81.  
  82. version = 0.1 # set version
  83.  
  84. # Do some work to work out if we included a server in the room name and default to @conference.server
  85. # Will also need to work out if the server was included on the nickname... It should've been but what the hell.
  86. self.rooms = []
  87.  
  88. for v in room.split(','):
  89. if v.find('@') is -1:
  90. self.rooms.append("%s@conference.%s" % (v, jid[(jid.find('@')+1):]))
  91. else:
  92. self.rooms.append(v)
  93.  
  94. self.nick = nick
  95. self.lastRoom = None
  96.  
  97. # Timer to use for ticks
  98. self.tickTock = 5
  99. self.timer = True
  100. self.SCHEDULE_SET = False
  101.  
  102. # Some basic session to keep
  103. self.conn = requests.Session()
  104.  
  105. # define some admins
  106. self.admins = ['psykzz','midge mo\'yb']
  107.  
  108. # Database connections
  109. '''
  110. self.db_host = 'psykzz.co.uk'
  111. self.db_user = 'daemo_bot'
  112. self.db_pass = 'jbQwe123'
  113. self.db_name = 'yapeal'
  114.  
  115. self.conn = mdb.connect(self.db_host, self.db_user,
  116. self.db_pass, self.db_name)
  117. self.db = self.conn.cursor(mdb.cursors.DictCursor)
  118. '''
  119.  
  120. # The session_start event will be triggered when
  121. # the bot establishes its connection with the server
  122. # and the XML streams are ready for use. We want to
  123. # listen for this event so that we we can initialize
  124. # our roster.
  125. self.add_event_handler("session_start", self.onStart)
  126.  
  127. # The groupchat_message event is triggered whenever a message
  128. # stanza is received from any chat room. If you also also
  129. # register a handler for the 'message' event, MUC messages
  130. # will be processed by both handlers.
  131. self.add_event_handler("groupchat_message", self.on_muc_message)
  132.  
  133. # What to do when we call close.
  134. self.add_event_handler("disconnected", self.onDisconnect)
  135.  
  136. # The groupchat_presence event is triggered whenever a
  137. # presence stanza is received from any chat room, including
  138. # any presences you send yourself. To limit event handling
  139. # to a single room, use the events muc::room@server::presence,
  140. # muc::room@server::got_online, or muc::room@server::got_offline.
  141. for room in self.rooms:
  142. self.add_event_handler("muc::%s::got_online" % room,
  143. self.on_muc_presence)
  144.  
  145. def onStart(self, event):
  146. """
  147. Process the session_start event.
  148. """
  149.  
  150. # Before we start the process we need to register the scheduler...
  151. if not self.SCHEDULE_SET:
  152. self.schedule('onTickTimer', # unique name for the timer
  153. self.tickTock, # seconds to delay before firing
  154. self.onTick, # function to execute
  155. #args=('xmpp'),
  156. repeat=True) # make the event happen every X seconds
  157. self.SCHEDULE_SET = True
  158.  
  159. for room in self.rooms:
  160. self.plugin['xep_0045'].joinMUC(room,
  161. self.nick,
  162. wait=True)
  163.  
  164. def onDisconnect(self, event):
  165. # Close the database connection.
  166. self.conn.close()
  167.  
  168. def onTick(self):
  169. try:
  170. # End if we shouldn't be running.
  171. if not self.timer:
  172. return
  173.  
  174. ## DO SOMETHING!
  175. #print "Test Tock"
  176. #self.ek_getNewKills()
  177. except:
  178. print "fuck - TickTock"
  179.  
  180. def on_muc_message(self, msg):
  181. """
  182. Process incoming message stanzas from any chat room. Be aware
  183. that if you also have any handlers for the 'message' event,
  184. message stanzas may be processed by both handlers, so check
  185. the 'type' attribute when using a 'message' event handler.
  186.  
  187. Whenever the bot's nickname is mentioned, respond to
  188. the message.
  189.  
  190. IMPORTANT: Always check that a message is not from yourself,
  191. otherwise you will create an infinite loop responding
  192. to your own messages.
  193.  
  194. This handler will reply to messages that mention
  195. the bot's nickname.
  196.  
  197. Arguments:
  198. msg -- The received message stanza. See the documentation
  199. for stanza objects and the Message stanza to see
  200. how it may be used.
  201. """
  202.  
  203.  
  204.  
  205. # Set the last room used to know where to reply to
  206. self.lastRoom = msg['from'].bare
  207.  
  208. # Check for any commamds.
  209. ###self._parse_cmds(msg)
  210.  
  211. try: # Is someone trying to get the bot to send a message? If so, do fuck all... cheeky cunts.
  212. sender = str(msg['from']).lower()
  213. sender = sender[sender.index('.com/')+5:]
  214.  
  215. if self.nick.lower() == sender:
  216. return
  217. except:
  218. return
  219.  
  220. try:
  221. self._parse_cmds(msg)
  222. except:
  223. print '>>> traceback <<<'
  224. traceback.print_exc()
  225. print '>>> end of traceback <<<'
  226. self._send_message("Nope, there is a bug with that.")
  227.  
  228. if msg['mucnick'] != self.nick and self.nick in msg['body']:
  229. self._send_message("I heard that, %s." % msg['mucnick'])
  230.  
  231. def on_muc_presence(self, presence):
  232. """
  233. Process a presence stanza from a chat room. In this case,
  234. presences from users that have just come online are
  235. handled by sending a welcome message that includes
  236. the user's nickname and role in the room.
  237.  
  238. Arguments:
  239. presence -- The received presence stanza. See the
  240. documentation for the Presence stanza
  241. to see how else it may be used.
  242. """
  243. if presence['muc']['nick'] != self.nick:
  244. print "%s - [%s] %s" % ( presence['muc']['room'][:presence['muc']['room'].find("@")], presence['muc']['role'][:1], presence['muc']['nick'] )
  245.  
  246. def _parse_cmds(self, message):
  247. """
  248. With an unproccessed message check if any of the matching commands
  249. match the start of the string and call the matching function.
  250.  
  251. Arguements:
  252. message -- The unproccessed message.
  253. Example "evedata psykzz | evedata 'midge moyb'"
  254. """
  255.  
  256. # Define commands
  257. self.cmds = ["help","version","restart","joinchannel","leavechannel","intel","translate","pickone"]
  258.  
  259. # Parse cmd
  260. _tmp = message['body'].lower().split(' ',1)
  261. cmd = _tmp[0]
  262.  
  263. # Check if the cmd exists...
  264. if not cmd in self.cmds:
  265. return # Return because it doesnt... eg do nothing...
  266.  
  267. # ReParse cmd
  268. cmd = "cmd_%s" % (cmd)
  269.  
  270. if len(_tmp) < 2:
  271. args = "no arguments"
  272. else:
  273. args = _tmp[1]
  274.  
  275. # Parse arguments
  276. ''' Testing attempts.
  277. arguments = shlex.split(
  278. _urllib.quote(
  279. args.encode("utf8")
  280. )
  281. )
  282. arguments = ["%s" % _urllib.unquote(arg).decode("utf8") for arg in arguments]
  283. #arguments = shlex.split(message.replace('\'','^').split(" ",1)[1])
  284. #arguments = ["%s" % arg.replace('^','\'') for arg in arguments]
  285. '''
  286. arguments = args
  287. #print arguments.decode("utf8","ignore")
  288. # Check if the function exists, is callable and call it.
  289. if hasattr(self, cmd) and callable(getattr(self, cmd)):
  290. #print u"Function called [%s] with (%s)" % (cmd,arguments.decode("utf8","ignore"))
  291. getattr(self, cmd)(arguments,message)
  292. else:
  293. #print "Function called [%s] with (%s)" % (cmd,arguments.decode("utf8","ignore"))
  294. print "Erorr! Function [%s] doesn't exist... shit." % (cmd)
  295.  
  296.  
  297. '''
  298. Parse Cmd shit.
  299. '''
  300.  
  301. def cmd_help(self, arguments, originalMessage):
  302. self._send_message("PLEH!. Available cmds:")
  303. self._send_message("- %s" % (', '.join(self.cmds)))
  304. return
  305.  
  306. def cmd_version(self, arguments, originalMessage):
  307. self._send_message("Version: %s. By PsyKzz" % self.version)
  308. return
  309.  
  310. def cmd_listchannels(self, arguments, originalMessage):
  311. if not self.isAdmin(originalMessage):
  312. self._send_message("No")
  313. return
  314.  
  315. originalMessage.reply((", ".join(self.rooms))).send()
  316. #print (", ".join(self.rooms))
  317. return
  318.  
  319. def cmd_restart(self, _meh, originalMessage):
  320. if not self.isAdmin(originalMessage):
  321. self._send_message("No")
  322. return
  323. self.disconnect(wait=True)
  324.  
  325. def cmd_joinchannel(self, args, originalMessage):
  326. if not self.isAdmin(originalMessage):
  327. self._send_message("No")
  328. return
  329.  
  330. args = "%s@conference.goonfleet.com" % (args)
  331. self.plugin['xep_0045'].joinMUC(args,
  332. self.nick,
  333. # If a room password is needed, use:
  334. # password=the_room_password,
  335. wait=True)
  336.  
  337. def cmd_leavechannel(self, args, originalMessage):
  338. if not self.isAdmin(originalMessage):
  339. self._send_message("No")
  340. return
  341.  
  342. if args == "no arguments":
  343. args = self.lastRoom
  344. args = "%s@conference.goonfleet.com" % (args)
  345. self.plugin['xep_0045'].leaveMUC(args,
  346. self.nick)
  347.  
  348. def cmd_keyinfo(self, charName, originalMessage, returnString=False):
  349. if not self.isAdmin(originalMessage):
  350. if not returnString:
  351. self._send_message("No")
  352. return
  353.  
  354. charid = self.eve_getID(charName)
  355. #ret = self.db_getKeyInfo(charid)
  356. if not returnString:
  357. self._send_message("Keys on file - %s" % ret)
  358. else:
  359. return ret
  360.  
  361. def cmd_pickone(self, text, originalMessage):
  362. _tmp = text.split(' or ')
  363. rand = random.randint(0, len(_tmp) )
  364. choice = _tmp[random.randint(0,len(_tmp)-1)] # Inclusive so remove one.
  365. self._send_message(choice)
  366.  
  367. def cmd_translate(self, text, originalMessage):
  368. url = "http://translate.google.com/translate_a/t"
  369. payload = {'client': 't', 'sl' : 'auto', 'tl': 'en','ie': 'UTF-8','multires': '1','text': text}
  370. r = requests.get(url, params=payload)
  371. self._send_message("- %s" % r.text[r.text.index("[\"")+2:r.text.index("\",\"")])
  372.  
  373. def cmd_translate2(self, text, originalMessage):
  374. url = "http://translate.google.com/translate_a/t"
  375. payload = {'client': 't', 'sl' : 'auto', 'tl': 'en','ie': 'UTF-8','multires': '1','text': text}
  376. r = requests.get(url, params=payload)
  377. self._send_message("- %s" % r.text[r.text.index("[\"")+2:r.text.index("\",\"")])
  378.  
  379. def cmd_bitcoin(self, convert, originalMessage):
  380. url = "http://btcrate.com/convert"
  381. payload = {'from': 'btc', 'to': convert.lower(), 'exch': 'mtgox', 'conv': 'google', 'amount': 1}
  382.  
  383. r = requests.get(url, params=payload)
  384. self._send_message("- 1 Bitcoin : %s %s" % (str(round(float(r.text[r.text.index(": \"")+3:r.text.index("\"}")]),2)), convert))
  385.  
  386. def cmd_intel(self, charName, originalMessage):
  387. # Get character ID and then data.
  388. try:
  389. charID = int(self.eve_getID(charName))
  390. except Exception:
  391. charID = 0
  392.  
  393. if charID == 0:
  394. self._send_message("Character ( %s ) Not Found." % charName)
  395. return
  396.  
  397. charData = self.eve_getCharData(charID)
  398. self._send_message("\n- %s" % (charData))
  399. #extraData = self.cmd_keyinfo(charName,originalMessage,True)
  400. #self._send_message("\n- %s\n- API Keys in DB (%s)" % (charData,extraData))
  401.  
  402.  
  403. def cmd_dbintel(self, charName, originalMessage):
  404. if not self.isAdmin(originalMessage):
  405. self._send_message("No")
  406. return
  407. # Get charID
  408. try:
  409. charID = int(self.eve_getID(charName))
  410. except Exception:
  411. charID = 0
  412.  
  413. if charID == 0:
  414. self._send_message("Character ( %s ) Not Found." % charName)
  415. return
  416.  
  417. # Get stuff
  418. #rows = self.db_getCharacterInfo(charID)
  419. data = "\n- %s [%s] <%s>\n- Skillpoints: %s\n- Balance: %sISK\n- DoB: %s" % \
  420. (rows['name'],rows['corporationName'],rows['allianceName'],rows['totalSP'],rows['balance'],rows['DoB'],)
  421.  
  422. self._send_message(data)
  423.  
  424.  
  425. '''
  426. Data base shit.
  427. '''
  428. '''
  429. def db_getKeyInfo(self, charID):
  430.  
  431. # Build the query, Assign params and execute
  432. self.db.execute("SELECT * \
  433. FROM v1_accountKeyBridge as keyb, \
  434. v1_utilRegisteredKey as utilk \
  435. WHERE keyb.keyID = utilk.keyID \
  436. AND keyb.characterID = %s \
  437. AND utilk.isActive = 1",
  438. (charID))
  439.  
  440. # Get number of rows.
  441. numrows = int(self.db.rowcount)
  442. return str(numrows)
  443. # loop through results and print.
  444. ##for i in range(numrows):
  445. ## row = self.db.fetchone()
  446. ## print row[0], row[1]
  447.  
  448. def db_getCharacterInfo(self, charID):
  449.  
  450. # Build the query, Assign params and execute
  451. self.db.execute("SELECT \
  452. cs.name, cs.corporationName, cs.allianceName, cs.balance, cs.DoB, sum(sp.skillpoints) as totalSP \
  453. FROM v1_charCharacterSheet as cs, \
  454. v1_charSkills as sp \
  455. WHERE cs.characterID = %s \
  456. AND cs.characterID = sp.ownerID \
  457. AND sp.published = 1",
  458. (int(charID)))
  459.  
  460. return self.db.fetchone()
  461. '''
  462. '''
  463. EVE Api shit.
  464. '''
  465. def eve_getCharData(self, charID):
  466.  
  467. url = "https://api.eveonline.com/eve/characterInfo.xml.aspx"
  468. payload = {'characterID': charID}
  469.  
  470. r = requests.get(url, params=payload)
  471. dom = parseString(r.text)
  472.  
  473. alliance = dom.getElementsByTagName('alliance')
  474. if not alliance:
  475. alliance = "No Alliance"
  476. else:
  477. alliance = dom.getElementsByTagName('alliance') [0].firstChild.nodeValue
  478.  
  479. result = "%s [%s] <%s> \n- Previous Corps : " % (
  480. dom.getElementsByTagName('characterName')[0].firstChild.nodeValue,
  481. dom.getElementsByTagName('corporation')[0].firstChild.nodeValue,
  482. alliance
  483. )
  484.  
  485. # In progress
  486. # Grab corporation IDs and then remove duplicates
  487. corpIDs = [node.getAttributeNode('corporationID').nodeValue for node in dom.getElementsByTagName('row')]
  488. corpIDs = list(set(corpIDs))
  489.  
  490. # Convert ID to Name (Old way)
  491. #corpNames = [self.eve_getName(name) for name in corpIDs]
  492.  
  493.  
  494. # Before converting... get a list of alliances from the corp ids.
  495.  
  496. ##for _id in corpIDs:
  497. ## allyName = self.eW_getAllianceName(_id)
  498.  
  499.  
  500. # Convert ID to Name (New way)
  501. corpNames = self.eve_getNames(corpIDs)
  502.  
  503. result = "%s %s" % ( result, ", ".join(corpNames) )
  504.  
  505. # Add zKillboard
  506. result = "%s\n- https://zkillboard.com/character/%s/" % ( result, charID )
  507. # get zBoard last kills
  508. #try:
  509. zBoardActivity = self.zkb_getKbActivity(charID)
  510. #finally:
  511. #zBoardKills = "Error getting Kills"
  512. result = "%s - [%s] Total Kills / Losses (7 Days)" % ( result, zBoardActivity )
  513.  
  514. # Add eveWho
  515. result = "%s\n- http://evewho.com/pilot/%s" % ( result, dom.getElementsByTagName('characterName')[0].firstChild.nodeValue.replace(" ","%20") )
  516.  
  517. return result
  518. #@cache_result
  519. def eve_getID(self, eveName):
  520.  
  521. url = "https://api.eveonline.com/eve/characterID.xml.aspx"
  522. payload = {'names': eveName}
  523. r = requests.get(url, params=payload)
  524. dom = parseString(r.text)
  525.  
  526. xmlTag = dom.getElementsByTagName('row')[0]
  527. atr = xmlTag.getAttributeNode('characterID')
  528. return atr.nodeValue
  529.  
  530. #@cache_result
  531. def eve_getName(self, eveID):
  532. url = "https://api.eveonline.com/eve/characterName.xml.aspx"
  533. payload = {'ids': eveID}
  534. r = requests.get(url, params=payload)
  535. dom = parseString(r.text)
  536.  
  537. xmlTag = dom.getElementsByTagName('row')[0]
  538. atr = xmlTag.getAttributeNode('name')
  539. return atr.nodeValue
  540.  
  541. #@cache_result
  542. def eve_getNames(self, eveID):
  543. url = "https://api.eveonline.com/eve/characterName.xml.aspx"
  544. payload = {'ids': ",".join(eveID)}
  545.  
  546. req = requests.Request('GET', 'https://api.eveonline.com/eve/characterName.xml.aspx', params=payload)
  547. r = req.prepare()
  548. r.url = r.url.replace("%2C",",")
  549. s = requests.Session()
  550. rec = s.send(r)
  551. #r = requests.get(url, params=payload)
  552. dom = parseString(rec.text)
  553. xmlTag = dom.getElementsByTagName('row')
  554. ret = [tag.getAttributeNode('name').nodeValue for tag in xmlTag]
  555. return ret
  556.  
  557. '''
  558. EVE WHO shit.
  559. '''
  560.  
  561. # The fuck is this...
  562. def eW_getAllianceName(self, corpID):
  563. url = "http://evewho.com/api.php"
  564. payload = {'type': 'corplist','id': corpID}
  565. r = requests.get(url, params=payload)
  566.  
  567. #Hack out the alliance id, even tho we are working with json
  568. print r.text
  569. _tmp = json.loads(str(r.text))
  570. print _tmp
  571. pass
  572.  
  573.  
  574. '''
  575. zKillboard Api shit.
  576. '''
  577.  
  578. def zkb_getNumKills(self, charID, monthsSince=1):
  579.  
  580. dateFrom = "%s0000" % (datetime.date.today() - datetime.timedelta(monthsSince*365/12)).isoformat().replace('-','') # 1 month ago
  581. self._send_message( "------ %s ------" % dateFrom)
  582. url = "http://zkillboard.com/kills/api/characterID/%s/pastSeconds/604800/orderDirection/asc/no-attackers/no-items/api-only/" % (charID)
  583. r = requests.get(url)
  584.  
  585. tmp = json.loads(str(r.text))
  586. return len(tmp)
  587.  
  588. def zkb_getNumLosses(self, charID, monthsSince=1):
  589.  
  590. dateFrom = "%s0000" % (datetime.date.today() - datetime.timedelta(monthsSince*365/12)).isoformat().replace('-','') # 1 month ago
  591. url = "http://zkillboard.com/api/losses/characterID/%s/pastSeconds/604800/orderDirection/asc/no-attackers/no-items/api-only/" % (charID)
  592. r = requests.get(url)
  593.  
  594. tmp = json.loads(str(r.text))
  595. return len(tmp)
  596.  
  597. def zkb_getKbActivity(self, charID, monthsSince=1):
  598.  
  599. dateFrom = "%s0000" % (datetime.date.today() - datetime.timedelta(monthsSince*365/12)).isoformat().replace('-','') # 1 month ago
  600. url = "http://zkillboard.com/api/characterID/%s/pastSeconds/604800/orderDirection/asc/no-attackers/no-items/api-only/" % (charID)
  601. r = requests.get(url)
  602.  
  603. tmp = json.loads(str(r.text))
  604. return len(tmp)
  605.  
  606. def isAdmin(self, user):
  607. _tmp = str(user['from']).lower()
  608. for admin in self.admins:
  609. if _tmp[_tmp.index('com/')+4:] == admin:
  610. return True
  611.  
  612. return False
  613.  
  614. def _send_message(self, message, recepient=False):
  615. """
  616. Custom function to send a message to current channel
  617. Literally used to automate my tasks.
  618. """
  619. if message is None:
  620. return
  621.  
  622. if not recepient:
  623. sendTo = self.lastRoom
  624. else:
  625. sendTo = recepient
  626.  
  627. self.send_message(mto=sendTo,
  628. mbody=message,
  629. mtype='groupchat')
  630.  
  631.  
  632. if __name__ == '__main__':
  633. # Setup the command line arguments.
  634. optp = OptionParser()
  635.  
  636. # Output verbosity options.
  637. optp.add_option('-q', '--quiet', help='set logging to ERROR',
  638. action='store_const', dest='loglevel',
  639. const=logging.ERROR, default=logging.INFO)
  640. optp.add_option('-d', '--debug', help='set logging to DEBUG',
  641. action='store_const', dest='loglevel',
  642. const=logging.DEBUG, default=logging.INFO)
  643. optp.add_option('-v', '--verbose', help='set logging to COMM',
  644. action='store_const', dest='loglevel',
  645. const=5, default=logging.INFO)
  646.  
  647. # JID and password options.
  648. optp.add_option("-j", "--jid", dest="jid",
  649. help="JID to use")
  650. optp.add_option("-p", "--password", dest="password",
  651. help="password to use")
  652. optp.add_option("-r", "--room", dest="room",
  653. help="MUC room to join")
  654. optp.add_option("-n", "--nick", dest="nick",
  655. help="MUC nickname")
  656.  
  657. opts, args = optp.parse_args()
  658.  
  659. # Setup logging.
  660. logging.basicConfig(level=opts.loglevel,
  661. format='%(levelname)-8s %(message)s')
  662.  
  663. if opts.jid is None:
  664. opts.jid = raw_input("Username: ")
  665. if opts.password is None:
  666. opts.password = getpass.getpass("Password: ")
  667. if opts.room is None:
  668. opts.room = raw_input("MUC room (multiple supported with commas): ")
  669. if opts.nick is None:
  670. opts.nick = raw_input("MUC nickname: ")
  671.  
  672. # Do some work to work out if we included a server in the room name and default to @conference.server
  673. # Will also need to work out if the server was included on the nickname... It should've been but what the hell.
  674. if not opts.jid.find('@') is -1:
  675. if opts.room.find('@') is -1:
  676. opts.room = "%s@conference.%s" % (opts.room, opts.jid[(opts.jid.find('@')+1):])
  677.  
  678. # Setup the IntelBot and register plugins. Note that while plugins may
  679. # have interdependencies, the order in which you register them does
  680. # not matter.
  681. xmpp = IntelBot(opts.jid, opts.password, opts.room, opts.nick)
  682. xmpp.register_plugin('xep_0030') # Service Discovery
  683. xmpp.register_plugin('xep_0045') # Multi-User Chat
  684. xmpp.register_plugin('xep_0199') # XMPP Ping
  685.  
  686. # Connect to the XMPP server and start processing XMPP stanzas.
  687. if xmpp.connect():
  688. # If you do not have the dnspython library installed, you will need
  689. # to manually specify the name of the server if it does not match
  690. # the one in the JID. For example, to use Google Talk you would
  691. # need to use:
  692. #
  693. # if xmpp.connect(('talk.google.com', 5222)):
  694. # ...
  695. xmpp.process(block=True)
  696. print("Done")
  697. else:
  698. print("Unable to connect.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement