def IQ_PROCESSING(client, iq): INFO["iq"] += 1 fromjid = iq.getFrom() if not fromjid or user_level(fromjid, fromjid.getStripped().lower()) < -99: raise xmpp.NodeProcessed() if iq.getType() == "get": nsType = iq.getQueryNS() result = iq.buildReply("result") query = result.getTag("query") if nsType == xmpp.NS_VERSION: query.setTagData("name", "BlackSmith mark.1") query.setTagData("version", "%s (r.%s)" % (CORE_MODE, BOT_REV)) query.setTagData("os", os_name) elif nsType == xmpp.NS_DISCO_INFO: anode = result.getTag("query") anode.addChild("identity", { "category": "client", "type": "bot", "name": "BlackSmith" }) for feature in XEPs: anode.addChild("feature", {"var": feature}) elif nsType == xmpp.NS_LAST: last = time.time() - LAST['time'] query.setAttr('seconds', int(last)) query.setData(LAST['cmd']) elif nsType == xmpp.NS_TIME: LocTime = time.strftime("%a, %d %b %Y %H:%M:%S") GMTime = time.strftime("%Y%m%dT%H:%M:%S (GMT)", time.gmtime()) tz = time.strftime("%Z") if BOT_OS == "nt": tz = tz.decode("cp1251") query.setTagData("utc", GMTime) query.setTagData("tz", tz) query.setTagData("display", LocTime) elif nsType == xmpp.NS_URN_TIME: #! TEST IT anode = result.addChild("time", namespace=xmpp.NS_URN_TIME) anode.setTagData("utc", strfTime("%Y-%m-%dT%H:%M:%SZ", False)) TimeZone = (time.altzone if time.daylight else time.timezone) anode.setTagData( "tzo", "%s%02d:%02d" % (((TimeZone < 0) and "+" or "-"), abs(TimeZone) / 3600, abs(TimeZone) / 60 % 60)) client.send(result) raise xmpp.NodeProcessed() call_efunctions("03eh", (iq, ))
def CheckFlood(): Flood.append(time.time()) if len(Flood) > 4: if (Flood[-1] - Flood[0]) < 9: globals()["Flood"] = [Flood.pop()] raise xmpp.NodeProcessed() else: Flood.pop(0)
def xhtml_handler(cl, msg): destination = msg.getTo().getStripped() source = msg.getFrom() if isinstance(source, (str, unicode)): logger.warning("Received message did not contain a valid jid: %s", msg) raise xmpp.NodeProcessed() source = source.getStripped() if source in Users and msg.getType() == "chat": user = Users[source] html = msg.getTag("html") if html and html.getTag("body"): # XHTML-IM! logger.debug("fetched xhtml image from %s", source) try: xhtml = mod_xhtml.parseXHTML(user, html, source, destination) except Exception: xhtml = False if xhtml: raise xmpp.NodeProcessed()
def xhtml_handler(cl, msg): destination = msg.getTo().getStripped() source = msg.getFrom().getStripped() if source in Users and msg.getType() == "chat": user = Users[source] html = msg.getTag("html") if html and html.getTag("body"): # XHTML-IM! logger.debug("fetched xhtml image from %s", source) try: xhtml = mod_xhtml.parseXHTML(user, html, source, destination) except Exception: xhtml = False if xhtml: raise xmpp.NodeProcessed()
def main_iq_handler(cl, iq): source = iq.getFrom() if WhiteList: if source and source.getDomain() not in WhiteList: sender( cl, utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, "You're not in the white-list")) raise xmpp.NodeProcessed() ping = iq.getTag("ping") if ping and ping.getNamespace() == xmpp.NS_PING: jidTo = iq.getTo() if jidTo == TransportID: sender(cl, iq.buildReply("result"))
def last_handler(cl, iq): jidFrom = iq.getFrom() jidTo = iq.getTo() source = jidFrom.getStripped() destination = jidTo.getStripped() id = vk2xmpp(destination) if id == TransportID: last = int(time.time() - startTime) name = IDENTIFIER["name"] elif source in Users and id in Users[source].friends: last = Users[source].vk.method("execute.getLastTime", {"uid": id}) or 0 last = int(time.time() - last) name = Users[source].vk.getUserData(id).get("name", "Unknown") else: raise xmpp.NodeProcessed() result = xmpp.Iq("result", to=jidFrom, frm=destination) result.setID(iq.getID()) result.setTag("query", {"seconds": str(last)}, xmpp.NS_LAST) result.setTagData("query", name) sender(cl, result)
def MESSAGE_PROCESSING(client, stanza): source = stanza.getFrom() INFO['msg'] += 1 instance = source.getStripped().lower() if user_level(source, instance) < -99: raise xmpp.NodeProcessed() isConf = (instance in GROUPCHATS) if not isConf and not has_access(source, 80, instance): if RSTR['VN'] == 'off': raise xmpp.NodeProcessed() CheckFlood() if (instance in UNAVAILABLE and not MSERVE) or stanza.getTimestamp( ): #"""Warning: i think these terms may cause problems""" raise xmpp.NodeProcessed() bot_nick = handler_botnick(instance) nick = source.getResource() if bot_nick == nick: raise xmpp.NodeProcessed() Subject = isConf and stanza.getSubject() body = stanza.getBody() if body: body = body.strip() elif Subject: body = Subject.strip() else: ##if not body: raise xmpp.NodeProcessed() if not isConf and instance not in ADLIST: if not '@conf' in instance: if instance in RSTR['BAN'] or RSTR['VN'] == 'off': raise xmpp.NodeProcessed() elif instance not in RSTR['AUTH'] and RSTR['VN'] == 'iq': sThread("rIQ", roster_check, (instance, body)) raise xmpp.NodeProcessed() if len(body) > INC_MSG_LIMIT: body = "%s[...] %d symbols limit." % (body[:INC_MSG_LIMIT].strip(), INC_MSG_LIMIT) stype = stanza.getType() if stype == 'error': code = stanza.getErrorCode() if code in ('500', '406'): if code == '406': if not isConf: raise xmpp.NodeProcessed() send_join_presece(instance, bot_nick) time.sleep(0.6) msg(source, body) raise xmpp.NodeProcessed() if Subject: call_efunctions("09eh", (instance, nick, Subject, body)) else: if stype != 'groupchat': if (stanza.getTag('request')): answer = xmpp.Message(source) answer.setTag("received", namespace=xmpp.NS_RECEIPTS).setAttr( "id", stanza.getID()) answer.setID(stanza.getID()) jClient.send(answer) type = 'private' else: type = 'public' if isConf and nick in GROUPCHATS[instance]: GROUPCHATS[instance][nick]['idle'] = time.time() command, Parameters, combody = '', '', body for app in [bot_nick + key for key in (':', ',', '>')]: if combody.startswith(app): combody = combody[len(app):].lstrip() break if not combody: raise xmpp.NodeProcessed() cmd = combody.split()[0].lower() if instance in COMMOFF and cmd in COMMOFF[instance]: raise xmpp.NodeProcessed() combody = MACROS.expand(combody, [source, instance, nick]) if instance in MACROS.macrolist.keys(): cmds = MACROS.gmacrolist.keys() + MACROS.macrolist[instance].keys() else: cmds = MACROS.gmacrolist.keys() if not combody: raise xmpp.NodeProcessed() combody = combody.split(None, 1) command = combody.pop(0).lower() if instance in PREFIX and cmd not in cmds: NotPfx = Prefix_state(body, bot_nick) if NotPfx or stype == 'chat': if not COMMANDS.has_key(command) and command.startswith( cPrefs): command = command[1:] else: command = command_Prefix(instance, command) if instance in COMMOFF and command in COMMOFF[instance]: raise xmpp.NodeProcessed() if COMMANDS.has_key(command): if combody: Parameters = combody.pop() INFO['cmd'] += 1 LAST[ 'cmd'] = u"Помощь по командам: «хелп» (последнее действие — «%s»)." % ( command) call_command_handlers(command, type, [source, instance, nick], Parameters, cmd) LAST['time'] = time.time() else: call_efunctions("01eh", (stanza, type, [source, instance, nick], body))
def PRESENCE_PROCESSING(client, stanza): fromjid = stanza.getFrom() INFO['prs'] += 1 conf = fromjid.getStripped().lower() if not has_access(fromjid, -5, conf): raise xmpp.NodeProcessed() Ptype = stanza.getType() if Ptype == 'subscribe': roster_subscribe(conf) if GROUPCHATS.has_key(conf): nick = fromjid.getResource() if Ptype == 'unavailable': reason = stanza.getReason() or stanza.getStatus() if GROUPCHATS[conf].has_key( nick) and GROUPCHATS[conf][nick]['ishere']: GROUPCHATS[conf][nick]['ishere'] = False scode = stanza.getStatusCode() if scode in ('301', '307') and nick == handler_botnick(conf): leave_groupchat(conf, u'Got %s code!' % str(scode)) text = (u'забанили' if scode == '301' else u'кикнули') delivery(u'Меня %s в "%s" и я оттуда вышел.' % (text, conf)) raise xmpp.NodeProcessed() elif scode == '303': full_jid = stanza.getJid() if not full_jid: full_jid = unicode(fromjid) jid = unicode(fromjid) else: full_jid = unicode(full_jid) jid = full_jid.split('/')[0].lower() Nick = stanza.getNick() try: GROUPCHATS[conf][Nick] = GROUPCHATS[conf].pop(nick) except KeyError: role = (stanza.getRole(), stanza.getAffiliation()) Time = time.time() GROUPCHATS[conf][nick] = { "role": role, "caps": stanza.getTagAttr("c", "node"), 'full_jid': full_jid, 'jid': jid, 'join_date': (that_day(), time.gmtime()), 'idle': Time, 'joined': Time, 'ishere': True } calc_acc(conf, jid, role) status = stanza.getShow() text = stanza.getStatus() call_efunctions( "04eh", (conf, nick, role[1], role[0], status, text)) else: GROUPCHATS[conf][Nick]['idle'] = time.time() call_efunctions("06eh", (stanza, conf, nick, Nick)) else: call_efunctions("05eh", (conf, nick, reason, scode)) #1 status_code_change(('idle', 'joined', "caps"), conf, nick) #0 elif Ptype in ('available', None): full_jid = stanza.getJid() if not full_jid: if MSERVE: if conf not in UNAVAILABLE: UNAVAILABLE.append(conf) jid = full_jid = unicode(fromjid) else: if conf not in UNAVAILABLE: UNAVAILABLE.append(conf) msg(conf, u'Отключаюсь до получения прав админа!') change_bot_status(conf, u'Отказываюсь работать без прав!', 'xa') raise xmpp.NodeProcessed() elif conf in UNAVAILABLE: if MSERVE: UNAVAILABLE.remove(conf) full_jid = unicode(full_jid) jid = full_jid.split("/", 1)[0].lower() else: if nick == handler_botnick(conf) and stanza.getAffiliation( ) in ('admin', 'owner'): UNAVAILABLE.remove(conf) msg(conf, u'Походу дали админа, перезахожу!') time.sleep(2) leave_groupchat(conf, 'Rejoin...') time.sleep(2) join_groupchat(conf, handler_botnick(conf)) raise xmpp.NodeProcessed() else: full_jid = unicode(full_jid) jid = full_jid.split("/", 1)[0].lower() ishere, role = GROUPCHATS[conf].has_key(nick), ( stanza.getRole(), stanza.getAffiliation()) if not (ishere and GROUPCHATS[conf][nick]['jid'] == jid and GROUPCHATS[conf][nick]['ishere']): GROUPCHATS[conf][nick] = { "role": role, "caps": stanza.getTagAttr("c", "node"), 'full_jid': full_jid, 'jid': jid, 'join_date': (that_day(), time.gmtime()), 'idle': time.time(), 'joined': time.time(), 'ishere': True } calc_acc(conf, jid, role) status = stanza.getShow() text = stanza.getStatus() call_efunctions("04eh", (conf, nick, role[1], role[0], status, text)) elif ishere and GROUPCHATS[conf][nick]["role"] != role: GROUPCHATS[conf][nick]["role"] = role calc_acc(conf, jid, role) call_efunctions("07eh", (conf, nick, role, stanza.getReason())) else: status = stanza.getShow() text = stanza.getStatus() priority = stanza.getPriority() call_efunctions("08eh", (conf, nick, status, priority, text)) elif Ptype == 'error': ecode = stanza.getErrorCode() if ecode: if ecode == '409': BOT_NICKS[conf] = '%s.' % (nick) send_join_presece(conf, handler_botnick(conf)) elif ecode in ('401', '403', '405'): leave_groupchat(conf, u'Got %s error code!' % str(ecode)) delivery(u'Ошибка %s, пришлось выйти из «%s»' % (ecode, conf)) elif ecode in ('404', '503'): try: ThrName = "rejoin-%s" % (conf.decode("utf-8")) if ThrName not in ThrNames(): composeTimer(360, error_join_timer, ThrName, (conf, )).start() except: pass if GROUPCHATS.has_key(conf): call_efunctions("02eh", (stanza, ))