天天看點

一個簡單有趣的微信聊天機器人聊聊

微信已經成了中國人生活中基本的通訊工具(除了那些自由開源人士以外),前兩天發現微信機器人的項目,其實早就有了。想着自己也做一個吧,順便加了一些小小的功能。

釋放我的機器人

微信掃一掃加他,跟他尬聊吧,把他拽到群裡調戲他。

一個簡單有趣的微信聊天機器人聊聊

qrcode.jpg

具體功能下面會介紹。

工具

  • 手機

    微信登陸必須得有手機端登陸才能使用網頁登陸,因為要掃一掃

  • Python 平台

    該項目基于 Python 開發,是以至少得來個嵌入式的開發闆,或者電腦,或者...雲伺服器 ;-),如果要保證長時間開啟與話,最好使用雲伺服器。

開發微信機器人

該項目基于 Github 上的

wxpy

,使用文檔在

這裡

。中文版的,是以我就不介紹這個怎麼使用了。簡單描述一下

建立機器人

from wxpy import *
bot = Bot()
           

注冊消息回複

機器人對好友、群聊中

at

他的人進行回複,在群聊中同時統計每個人的發言次數和第一次發言的時間,将這些資訊實時存儲在本地,以防程式錯誤導緻資料丢失。

消息回複中的機器人使用

圖靈機器人

, 可免費申請 API,調用他。也可以使用

小 I 機器人

。這兩個都是深度整合在項目裡的。

@bot.register([Friend, Group])
def reply_friend(msg):
    """
    消息自動回複
    """
    print(msg)
    if isinstance(msg.chat, Group):
        group = msg.chat.name
        name = msg.member.name
        if group in stat:
            if name in stat[group]['count']:
                stat[group]['count'][name] += 1
            else:
                stat[group]['count'][name] = 1
            flag = True
            for rank in stat[group]['rank']:
                if name == rank['name']:
                    flag = False
                    break
            if flag:
                stat[group]['rank'].append({'name': name, 'time': time.strftime("%H:%M:%S", time.localtime())})
        else:
            stat[group] = {"count": {name: 1}, 'rank': [{'name': name, 'time': time.strftime("%H:%M:%S", time.localtime())}, ]}
        if msg.text == "發言排行榜":
            g = bot.groups().search(group)[0]
            if not stat[g.name]:
                return
            msg_text = ""
            index = 1
            count = stat[g.name]['count']
            for name in sorted(count, key=lambda x: count[x], reverse=True):
                # print("{}: {} {}".format(index, rank['name'], rank['time']))
                msg_text += "{}: {} 發言了 {} 次\n".format(index, name, count[name])
                index += 1
            if msg_text:
                msg_text = "發言排行榜:\n" + msg_text
                g.send(msg_text)
        if msg.text == "起床排行榜":
            g = bot.groups().search(group)[0]
            if not stat[g.name]:
                return
            msg_text = ""
            index = 1
            for rank in stat[g.name]['rank']:
                # print("{}: {} {}".format(index, rank['name'], rank['time']))
                msg_text += "{}: {} {}\n".format(index, rank['name'], rank['time'])
                index += 1
            if msg_text:
                msg_text = "起床排行榜:\n" + msg_text
                g.send(msg_text)
        with open('stat.json', 'w') as fh:
            fh.write(json.dumps(stat))
        if not msg.is_at:
            return
    return tuling_auto_reply(msg)
           

自動接受好友申請

@bot.register(msg_types=FRIENDS)
def auto_accept_friends(msg):
    """
    自動接受好友請求
    """
    # 接受好友請求
    new_friend = msg.card.accept()
    # 向新的好友發送消息
    new_friend.send('哈哈,我們現在是超級好的好朋友了呢~~')
           

添加計劃任務

光回複怎麼夠,還要做一些小小的有趣的功能,我這裡添加了兩個統計,一個是起床時間統計,另一個是發言統計。

當天群聊的使用者第一次發言作為起床時間,雖然有些不嚴謹,但畢竟功能是受限制的。

然後每天的 9 點釋出一次起床排行榜, 20 點釋出一次發言排行榜。當然其實主動發送 “起床排行榜”、“發言排行榜” 也會回複目前的排行。

起床排行榜

一個簡單有趣的微信聊天機器人聊聊

rank_getup.jpg

發言排行榜

一個簡單有趣的微信聊天機器人聊聊

rank_speak.jpg

實作

class ScheduleThread(threading.Thread):
    """
    計劃任務線程
    """
    def run(self):
        global schedule_time
        global bot
        global stat
        while 1:
            time.sleep(300)
            cur_hour = time.strftime("%H", time.localtime())
            # print("cur:{}\tschedule:{}".format(cur_hour, schedule_time))
            if cur_hour == schedule_time:
                continue
            elif cur_hour == '09':
                for group in bot.groups():
                    print(group.name)
                    if not stat[group.name]:
                        continue
                    msg_text = ""
                    index = 1
                    for rank in stat[group.name]['rank']:
                        # print("{}: {} {}".format(index, rank['name'], rank['time']))
                        msg_text += "{}: {} {}\n".format(index, rank['name'], rank['time'])
                        index += 1
                    if msg_text:
                        msg_text = "排行日報\n起床排行榜:\n" + msg_text
                        group.send(msg_text)
            elif cur_hour == '20':
                for group in bot.groups():
                    print(group.name)
                    if not stat[group.name]:
                        continue
                    msg_text = ""
                    index = 1
                    count = stat[group.name]['count']
                    for name in sorted(count, key=lambda x: count[x], reverse=True):
                        # print("{}: {} {}".format(index, rank['name'], rank['time']))
                        msg_text += "{}: {} 發言了 {} 次\n".format(index, name, count[name])
                        index += 1
                    if msg_text:
                        msg_text = "排行日報\n發言排行榜:\n" + msg_text
                        group.send(msg_text)
            elif cur_hour == '00':
                stat = dict()
                with open('stat.json', 'w') as fh:
                    fh.write('')
            schedule_time = cur_hour
           

聊聊

展示兩個機器人互相尬聊的情況是怎麼樣的。

一個簡單有趣的微信聊天機器人聊聊

chat.jpg

部署

建立機器人時添加一個

console_qr

參數,

True

時表示在終端顯示二維碼,

False

表示用圖檔程式打開二維碼。按情況來,如果在沒有界面的雲伺服器上,那就在終端打開,如果隻能連 tty ,那最好的辦法就是生成一張圖檔,放到指定的 FTP 或者雲盤目錄,然後本地打開掃描,或者建個簡單的 HTTP 伺服器展示圖檔,方法很多,根據自己情況來吧。

原文位址:

一個簡單有趣的微信聊天機器人

我的部落格:

時空路由器