chatrug / tests /


import crg
import traceback

a = crg.Avatar('moriarty_test', 'testtesttest')
print "avatar created"

def onAuth(avatar, error):
    print "error '%s' on authing avatar %s with name %s" % (error, avatar,
    crg.listChannels(avatar, onList)

def onList(avatar, channels, error):
    print "onList error: '%s' on avatar %s. Channels: %s" % (error,, ", ".join("%s (%d)" % (, k) for k, v in channels.items()))
    crg.joinChannel(avatar, channels[6], onJoin)
    crg.receiveMessages(avatar, onMessage)

def onJoin(avatar, channel, error):
    print "on Join error: '%s', channel: %s, avatar: %s" % (error,,
    #crg.sendMessage(avatar, channel, crg.Message("тест"), onSent)

def onSent(avatar, channel, message, error):
    print "onSent error: '%s', message: %s, channel: %s, avatar: %s" % (error, message.text(),,

def cmdPing(avatar, channel, msg, **kwargs):
    crg.sendMessage(avatar, channel, crg.Message("pong", msg.sender() if channel.isPrivate() else ""), onSent)

def cmdHelp(avatar, channel, msg, **kwargs):
    crg.sendMessage(avatar, channel, crg.Message("Команды: ping, погода [город]", msg.sender() if channel.isPrivate() else ""), onSent)

def cmdWeather(avatar, channel, msg, text, **kwargs):
    def getWeather(city):
        def s(c):
            return u"Температура: %s, %s, %s, %s" % (c["temp_c"], c["condition"], c["humidity"], c["wind_condition"])
        def s2(c):
            return u"%s: %s" % (c["day_of_week"], c["condition"])

        import pywapi
        w = pywapi.get_weather_from_google(city, hl="ru")
        return (u"%s. %s" % (s(w["current_conditions"]), u". ".join(s2(x) for x in w["forecasts"]))).encode("utf-8")
    parts = text.strip().split(' ')
    if len(parts) == 1:
        city = "Москва"
        city = parts[1].strip()
    print "weather for %s (%s)" % (city, text)
    crg.sendMessage(avatar, channel, crg.Message(getWeather(city), msg.sender() if channel.isPrivate() else ""), onSent)

def get_cmd(avatar, chl, msg):
    def nop(*args, **kwargs): pass
    cmds = {"ping": cmdPing, "погода": cmdWeather}

    text = None
    if chl.isPrivate():
        text = msg.text()
    elif msg.text().startswith( + ": "):
        text = msg.text()[len( + ": "):]
        return nop, text

    for k, v in cmds.iteritems():
        if text.lower().startswith(k):
            return v, text
    return cmdHelp, text
    #return cmds.get(text, cmdHelp)

def onMessage(avatar, msg):
        print "%s: %s" % (msg.sender(), msg.text())
        if msg.sender() != "-SYS" and msg.sender() !=
            chl = crg.getChannel(avatar, msg)
            c, t = get_cmd(avatar, chl, msg)
            c(avatar = avatar, channel = chl, msg = msg, text = t)

        print traceback.format_exc()

def onIdle():
    #print "onIdle"

print "auth registered"

print "mainlooped"