示例#1
0
文件: eqbot.py 项目: codl/eqbot
def nick(e, bot):
    if auth(e.source) >= HOP:
        words = e.msg.split()
        if len(words) < 2:
            bot.reply(e, "Usage : !nick newnick")
        else:
            bot.irc.setNick(words[1])
示例#2
0
def reload_(bot, irc, cur):
    if not isinstance(cur.params['lang'], bool):
        t = time.time()
        import lang
        if isinstance(cur.params['lang'], unicode):
            exec("reload(lang.%s)" % cur.params['lang'])
            t = time.time() - t
            bot.reply("reloaded lang.%s in %0.3f ms" % (cur.params['lang'], t))
        elif isinstance(cur.params['lang'], list):
            for l in cur.params['lang']:
                try:
                    exec("reload(lang.%s)" % l)
                except AttributeError:
                    bot.privnotice("module %s not found", l)
            t = time.time() - t
            langs = ", ".join(cur.params['lang'])
            bot.privnotice("reloaded %s langs in %.4f ms", langs, t)
        if not cur.params.arguments(): return

    if cur.params['replies']:
        module = File("replies.py", "lang").load()
        self.replies = module

    if cur.args == "bot":
        import bot
        exec("reload(bot)")
        return
    short_names = {"fr": "freenode", "wm": "wikimedia", "cm": "common"}

    if "." in cur.args:
        folder, name = cur.args.split(".")
        folder = short_names[folder] if folder in short_names else bot.folders[
            0]
    else:
        folder = bot.folders[0]
        name = cur.args
    print cur.args, name, folder

    modules = os.path.join(os.getcwd(), folder)
    if not name:
        bot.privnotice("module name expected")
        return
    elif name + ".py" not in os.listdir(modules):
        bot.privnotice("unknown module")
        return
    module = getattr(__import__("%s.%s" % (folder, name)), name)
    reload(module)
    bot.load._register(vars(module))
    bot.load._bindrules()
    for priority in bot.commands:
        bot.commands[priority].update(bot.load.commands[priority])

    if hasattr(module, '__file__'):
        mtime = os.path.getmtime(module.__file__)
        modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(mtime))
    else:
        modified = 'unknown'
    msg = bot.translate('%r (version: %s)')
    msg = msg % (module, modified)
    bot.reply(msg)
示例#3
0
文件: eqbot.py 项目: codl/eqbot
def part(e, bot):
    if auth(e.source) >= HOP:
        words = e.msg.split()
        if len(words) < 2:
            bot.reply(e, "Usage : !part #channel")
        else:
            bot.part(words[1])
示例#4
0
文件: eqbot.py 项目: codl/eqbot
def roll(e, bot):
    total = 0
    msg = "Rolling "
    dice = e.msg.split()[1:]
    totaldice = 0
    for die in dice:
        try:
            spec = re.match("(\\d+)?d(\\d+)", die, re.I).groups("1")
            num, sides = int(spec[0]), int(spec[1])
            if num == 0:
                continue
            if sides >= 100:
                e.reply("That die is way too big. How do you expect me to even lift it?")
                return
            msg += str(num) + " " + str(sides) + "-sided di" + ("ce" if num > 1 else "e") + ":"
            for i in range(num):
                res = random.randint(1, sides)
                msg += " " + str(res)
                total += res
                totaldice+=1
                if totaldice >= 100:
                    e.reply("Rolling a few handfuls of dice: Total: a few millions, maybe more")
                    return
            bot.reply(e, msg)
            msg = "        " # for alignment
        except LookupError:
            pass
    if totaldice > 1:
        bot.reply(e, "Total: " + str(total))
示例#5
0
 def test_reply_function(self):
     submission = praw.objects.Submission.from_id(TestAPI.reddit, TestAPI.submission_id)
     comment = submission.comments[0]
     text = "Testing reply function"
     expected_text = text + bot.disclaimer
     bot.reply(comment, text)
     self.assertEqual(TestAPI.helper_search_for_comment(expected_text), expected_text)
示例#6
0
文件: eqbot.py 项目: codl/eqbot
def join(e, bot):
    if auth(e.source) >= HOP:
        words = e.msg.split()
        if len(words) < 2:
            bot.reply(e, "Usage : !join #channel [loudness]")
        elif len(words) == 2:
            bot.join(words[1])
        else:
            bot.join(words[1], int(words[2]))
示例#7
0
文件: eqbot.py 项目: codl/eqbot
def do(e, bot):
    words = e.msg.split()
    if len(words) < 3:
        bot.reply(e, "Usage : !do #channel action")
        if auth(e.source) >= HOP:
            bot.reply(e, "        !do nick action")
        return
    if auth(e.source) >= HOP or e.args[0][0] in "#&":
        bot.sendMsg(words[1], irc.action(" ".join(words[2:])))
示例#8
0
文件: eqbot.py 项目: codl/eqbot
def poemm(e, bot):
    words = e.msg.split()[1:]
    if len(words) < 1:
        words.append(random.choice(startingwords))
    while len(words) == 0 or words[-1] != "":
        words.append(tripletget(" ".join(words[-2:])))
    if words[-1] == "": words = words[:-1]
    msg = " ".join(words)
    bot.reply(e, msg)
示例#9
0
文件: eqbot.py 项目: codl/eqbot
def rfc(e, bot):
    if len(e.args != 1):
        e.reply("Usage: !rfc <ID>")
        return
    url = "https://tools.ietf.org/html/rfc" + e.args[0]
    title = fetchTitle(url)
    if not title:
        bot.reply(e, "No such RFC standard.")
        return
    bot.reply(e, title + " " + url)
示例#10
0
文件: eqbot.py 项目: codl/eqbot
def feature(e, bot):
    if auth(e.source) >= HOP:
        tids = e.args
        if len(tids) == 0 and bot.lastTid:
            tids = (bot.lastTid,)
        for tid in tids:
            try:
                int(tid)
                bot.reply(e, os.popen("sudo -u eqbeats-pub EQBEATS_DIR=/var/lib/eqbeats /opt/eqbeats/libexec/eqbeats/fqueue " + tid + " 2>&1").read())
            except (TypeError, ValueError):
                continue
示例#11
0
文件: eqbot.py 项目: codl/eqbot
def plot(e, bot):
    words = e.msg.split(" ")
    swapped = False
    for i in range(len(words)): # how unpythonic D:
        if words[i] == "plot":
            words[i] = "intrigue"
            swapped = True
        elif words[i] == "PLOT":
            words[i] = "INTRIGUE"
            swapped = True
    if swapped: bot.reply(e, "<" + e.sourceNick + "> " + " ".join(words))
示例#12
0
文件: eqbot.py 项目: codl/eqbot
def backflip(e, bot):
    if bot.bfcounter < 12:
        bot.reply(e, irc.action("does "+" ".join(adjective())+" backflip and lands on its "+bodypart()))
        bot.bflast = time.time()
        bot.bfcounter += 1
        if bot.bflast + 60 < time.time():
            bot.bfcounter = 1
    elif bot.bfcounter == 12:
        bot.bfcounter = 13
        bot.reply(e, irc.action("is too tired to backflip right now"))
        time.sleep(60)
        bot.bfcounter = 0
示例#13
0
文件: eqbot.py 项目: codl/eqbot
def mail(e, bot):
    db = getdb()
    c = db.cursor()
    if len(e.args) < 2:
        bot.reply(e, "Syntax : !mail nick message")
        return
    nick = e.args[0]
    msg = " ".join(e.msg.split(" ")[2:]) # avoid collapsing whitespace
    private = (e.channel == None)
    c.execute("INSERT INTO mail (source, dest, private, msg, time) VALUES (?, ?, ?, ?, ?)", (e.sourceNick, nick, private, msg, time.time()))
    db.commit()
    bot.reply(e, "Message stored!")
示例#14
0
文件: eqbot.py 项目: codl/eqbot
def say(e, bot):
    words = e.msg.split()
    if len(words) < 3:
        bot.reply(e, "Usage : !say #channel message")
        if auth(e.source) >= HOP:
            bot.reply(e, "        !say nick message")
        return
    if auth(e.source) >= HOP or e.args[0][0] in "#&":
        if words[1].lower() == "chanserv" and words[2].lower() == "kick" and words[3].lower() == "#eqbeats":
            e.reply("Do it yourself.")
        else:
            bot.sendMsg(words[1], " ".join(words[2:]))
示例#15
0
文件: eqbot.py 项目: codl/eqbot
def getvalue(e, bot):
    variables = re.findall("[^ \\t]+==", e.msg)
    db = getdb()
    c = db.cursor()
    for var in variables:
        var = var[:-2]
        c.execute("SELECT name, value FROM variables WHERE name LIKE ?", (var,))
        row = c.fetchone()
        if row:
            var = row[0]
            val = str(row[1])
        else:
            val = "0"
        msg = "Karma for "+var+" : "+val
        bot.reply(e, msg)
示例#16
0
def response():
    answer = "--no response calculated--"
    if request.method == 'POST':
        try:
            data = json.loads(request.data)
            text = data['entry'][0]['messaging'][0]['message'][
                'text']  # Incoming Message Text
            print(text)
            answer = bot.reply(text)
            sender = data['entry'][0]['messaging'][0]['sender'][
                'id']  # Sender ID
            payload = {
                'recipient': {
                    'id': sender
                },
                'message': {
                    'text': answer
                }
            }  # We're going to send this back
            r = requests.post(
                'https://graph.facebook.com/v2.6/me/messages/?access_token=' +
                token,
                json=payload)  # Lets send it
        except Exception as e:
            print(e)  # something went wrong

    elif request.method == 'GET':  # For the initial verification
        if request.args.get('hub.verify_token') == '<facebook-secret-key>':
            return request.args.get('hub.challenge')
        return "Wrong Verify Token"

    return answer  #Not Really Necessary
示例#17
0
文件: eqbot.py 项目: codl/eqbot
def deliverMail(e, bot):
    nick = e.msg if e.type == irc.NICK else e.sourceNick
    db = getdb()
    c = db.cursor()
    c.execute("SELECT source, msg, private, time FROM mail WHERE dest LIKE ?", (nick,))
    messages = c.fetchall()
    c.execute("DELETE FROM mail WHERE dest LIKE ?", (nick,))
    for m in messages:
        msg = nick + ": Mail from " + m[0]
        if m[3]:
            msg += " sent %s ago" % (relativetime(time.time() - int(m[3])))
        msg += ": " + m[1]
        if m[2] or not e.channel:
            bot.sendMsg(nick, msg)
        else:
            bot.reply(e, msg)
    db.commit()
示例#18
0
文件: eqbot.py 项目: codl/eqbot
def lightsaber(e, bot):
    words = e.msg.split(" ")
    swapped = False
    for i in range(len(words)):
        if words[i] in ("VIBRATOR", "D***O"):
            words[i] = "LIGHTSABER"
            swapped = True
        elif words[i] in ("VIBRATORS", "DILDOS"):
            words[i] = "LIGHTSABERS"
            swapped = True
        elif words[i].lower() in ("vibrator", "d***o"):
            words[i] = "lightsaber"
            swapped = True
        elif words[i].lower() in ("vibrators", "dildos"):
            words[i] = "lightsabers"
            swapped = True
    if swapped: bot.reply(e, "<" + e.sourceNick + "> " + " ".join(words))
示例#19
0
def lambda_handler(event, context):
    for record in event['Records']:
        dynamodb = boto3.resource('dynamodb', region_name=REGION)
        table = dynamodb.Table('WhatToWatchDB')
        response2 = table.get_item(Key={'Field': 'consumer_key'})
        consumer_key = response2['Item']['StringValue']
        response3 = table.get_item(Key={'Field': 'consumer_secret'})
        consumer_secret = response3['Item']['StringValue']
        response4 = table.get_item(Key={'Field': 'access_token'})
        access_token = response4['Item']['StringValue']
        response5 = table.get_item(Key={'Field': 'access_token_secret'})
        access_token_secret = response5['Item']['StringValue']
        api = bot.config(consumer_key, consumer_secret, access_token,
                         access_token_secret)
        bot.reply(api, record['messageAttributes']['user']['stringValue'],
                  record['messageAttributes']['id']['stringValue'],
                  record['messageAttributes']['film']['stringValue'])
    return {'statusCode': 200, 'body': json.dumps(json.dumps('success'))}
示例#20
0
def dialogflow():
    data = request.get_json(silent=True)
    sentence = data['queryResult']['queryText']
    bot_reply = bot.reply(sentence)

    reply = {
        "fulfillmentText": bot_reply,
    }

    return jsonify(reply)
示例#21
0
文件: eqbot.py 项目: codl/eqbot
def violence(e, bot): # never the answer
    if(e.type == irc.ACTION and re.search("(hits|kicks|slaps|punches|crushes|maims|harms|shoots|stabs) " + i.nick, e.msg, re.I)):
        if e.channel == "#eqbeats" and random.random() < 0.1:
            bot.reply(e, "You thought you could abuse old EqBot, that pushover. Well, new EqBot is not going to have any of that!")
            time.sleep(0.5)
            bot.sendMsg("ChanServ", "kick #eqbeats " + e.sourceNick)
        else:
            bot.reply(e, random.choice((
                "Ow!",
                "Stop that!",
                "HALP!",
                ":(",
                "You broke my " + bodypart() + "!",
                "I don't like you. :(",
                irc.action("cries"),
                irc.action("flails"),
                irc.action("whimpers"),
                irc.action("whines"),
                irc.action("flees"))
            ))
示例#22
0
文件: eqbot.py 项目: codl/eqbot
def choice(e, bot):
    choices = e.msg.split(" or ")
    choices[0] = " ".join(choices[0].split(" ")[1:])
    if len(choices) == 1:
        choices = e.msg.split()[1:]
    if any(pony in choices for pony in ("ponies", "PONIES", "pony", "PONY", "pone", "PONE", "poni", "PONI", "mlp", "MLP")):
        bot.reply(e, b"\02Ponies, obviously.")
    elif len(choices) <= 1:
        bot.reply(e, "Not much of a choice, eh?")
    else:
        bot.reply(e, random.choice(choices))
示例#23
0
def index():
    if not current_user.is_authenticated:
        return render_template('login.html')
    else:
        if request.method == 'POST':
            if session.get('ayat') is not None:
                session.pop('ayat',None)
            message = Message(request.form['message'], datetime.now().strftime('%H:%M'), current_user.username)
            if message.text:
                response = Message(bot.reply(current_user.username, message.text), datetime.now().strftime('%H:%M'), 'bot')
                newConv = Converation(user=current_user.username, userMsg=message.text, botReply=response.text,sessNum=current_user.sessNum)
                try:
                    db.session.add(newConv)
                    db.session.commit()
                except:
                    return "Database addition error occurred"
                if session.get('chat') is not None:
                    session['chat'] = session['chat'] + [message.__dict__, response.__dict__]
                else:
                    session['chat'] = [message.__dict__, response.__dict__]
        return render_template('index.html')
示例#24
0
文件: eqbot.py 项目: codl/eqbot
def _search(e, bot, q):
    try:
        id = int(q)
        t = eqbeats.track(id)
        if t:
            e.reply(eqbeats.ppTrack(t))
            bot.lastTid = str(id)
            return
        else:
            e.reply("No tracks found.")
    except ValueError:
        if not q == "":
            tracks = eqbeats.search(q)[:3]
            for t in tracks[:2]:
                bot.reply(e, eqbeats.ppTrack(t))
            if len(tracks) == 0:
                bot.reply(e, "No tracks found.")
            elif len(tracks) == 1:
                bot.lastTid = str(tracks[0]['id'])
            elif len(tracks) == 3:
                bot.reply(e, "and more at https://eqbeats.org/tracks/search?%s" % up.urlencode({'q': q}))
示例#25
0
def get_bot_response():
    userText = request.args.get('msg')
    return str(bot.reply(userText))
示例#26
0
文件: eqbot.py 项目: codl/eqbot
def rejoice(e, bot):
    bot.reply(e, "yay")
示例#27
0
文件: eqbot.py 项目: codl/eqbot
def louder(e, bot):
    bot.reply(e, b"\002yay")
示例#28
0
文件: eqbot.py 项目: codl/eqbot
def louder_(e, bot):
    bot.reply(e, b"\002Yay!")
示例#29
0
文件: eqbot.py 项目: codl/eqbot
def kindness(e, bot):
    if(e.type == irc.ACTION and re.search("(hugs|snuggles|pets|brohoofs|pats) " + i.nick, e.msg, re.I)):
        bot.reply(e, "<3")
示例#30
0
文件: eqbot.py 项目: codl/eqbot
def batman(e, bot):
    bot.reply(e, "I'm the " + adjective()[1] + " Batman.")
示例#31
0
文件: eqbot.py 项目: codl/eqbot
def parensdundundun(e, bot):
    bot.reply(e, "(dun dun duuun)")
示例#32
0
文件: eqbot.py 项目: codl/eqbot
def rand_track(e, bot):
    bot.reply(e, eqbeats.ppTrack(eqbeats.random()))
示例#33
0
def timed_job():
    bot.tweet()
    bot.reply()
示例#34
0
文件: eqbot.py 项目: codl/eqbot
def debug_auths(e, bot):
    if auth(e.source) == OP:
        for nick, level in bot.userlevel.items():
            bot.reply(e, nick + ": " + str(level))
示例#35
0
文件: eqbot.py 项目: codl/eqbot
def url(e, bot):
    title = fetchTitle(e.groups[0])
    if title:
        bot.reply(e, b"\02" + title.encode("utf_8") + b"\2 posted by " + e.sourceNick.encode("utf_8"))
示例#36
0
文件: eqbot.py 项目: codl/eqbot
def dundundun(e, bot):
    bot.reply(e, "DUN DUN DUUUN")
示例#37
0
文件: eqbot.py 项目: codl/eqbot
def flipcoin(e, bot):
    bot.reply(e, "tails" if random.random() < 0.5 else "heads")